I need to implement the following function. I’m open to using the best class, but I’m not sure whether I should use SortedSet or TreeSet (as in Set myEmailsAscending = new TreeSet(new DateAscendingComparator()); // emails are always in ascending order).
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
}
Is that the proper syntax to choose comparator?
I’d like to avoid creating multiple Comparator classes so is there a way to do this?
There are several issues:
You should use
equals()for string comparison and not==.The usage of
newis wrong. I’d suggest the following:Note how the
newhas been moved inside theifblocks.As an alternative to all this, you could use a
SortedSet<Email>with the appropriate comparator. The set will be automatically kept sorted in the correct order.