我需要实现以下功能。我愿意使用最好的类,但我不确定我应该使用 SortedSet 还是 TreeSet(如 Set myEmailsAscending = new TreeSet(new DateAscendingComparator()); // 电子邮件始终按升序排列)。
public void addEmail(Email email)//The prototype isn't to be altered.
{
Comparator comp;
if(getCurrentSortingMethod()=="DateDescending") comp=DateDescendingComparator;
else if(getCurrentSortingMethod()=="DateAscending") comp=DateAscendingComparator;
...//other comparators
int index = Collections.binarySearch(getEmails(), email, new comp());// Search where to insert according to the current sorting method.
getEmails().add(-index-1, email);}// Add the item to the list
}
这是选择比较器的正确语法吗?我想避免创建多个 Comparator 类,那么有没有办法做到这一点?