我需要实现以下功能。我愿意使用最好的类,但我不确定是否应该使用 SortedSet 还是 TreeSet (如 Set myEmailsAscending = new TreeSet(new DateAscendingComparator());//emails 始终按升序排列)。
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
}
这是选择比较器的正确语法吗? 我想避免创建多个比较器类,那么有没有办法做到这一点?
最佳答案
有几个问题:
您应该使用equals()
用于字符串比较而不是 ==
.
new
的用法是错的。我建议如下:
Comparator comp;
if (getCurrentSortingMethod().equals("DateDescending")) {
comp = new DateDescendingComparator();
} else if (getCurrentSortingMethod().equals("DateAscending")) {
comp = new DateAscendingComparator();
} ...
int index = Collections.binarySearch(getEmails(), email, comp);
注意new
是如何已移至 if
内 block 。
作为所有这些的替代方案,您可以使用 SortedSet<Email>
与适当的比较器。该集合将自动按正确的顺序排序。
关于java - 如何实现基于多个比较器的 add() 排序列表;参数化比较器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10303012/