java - 如何实现基于多个比较器的 add() 排序列表;参数化比较器?

标签 java insert comparator

我需要实现以下功能。我愿意使用最好的类,但我不确定是否应该使用 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/

相关文章:

java - BeanComparator 生成 NoClassDefFoundError

java - 使用比较器对数据结构进行排序

mysql - 为什么 MySql 不能对 INSERT 语句使用 PARTITION 修剪?

mysql - 为什么 ENUM 不在 MySQL 中存储多个值?

python - 使用 Stargate Rest 将数据插入 Hbase

java - 如何排除打包为应用程序的 uber jar 的 jar 文件

java - TreeSet 中执行 Comparator 后删除的元素

java - 如何使用 SAX 解析器识别 xml 标签(元素)是否有子元素?

java - 未找到 int 数组中的元素(虽然应该找到)

java - Java 中带有 "static"类的 Fluent API