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

标签 java comparator treeset

我的代码很平静:

final SortedSet<NisType> lAllNNisType = new TreeSet<NisType>(new NisTypeComparator());
lAllNisType.addAll(pAllNisType); // where pAllNisType is of type ArrayList<NisType>

那是我的比较器类:

  private class NisTypeComparator implements Comparator<NisType> {

    @Override
    public int compare(NisType pNisType, NisType pNisType2) {
       if (pNisType.getPrio()>pNisType2.getPrio())
         return 1;
       else if (pNisType.getPrio()<pNisType2.getPrio())
         return -1;
       else
         return 0;
    }
  }

我的ArrayList pAllNisType填充了6个不同的对象(基于equals和hashCode方法)。 尽管如此,执行此行后:

lAllNisType.addAll(pAllNisType);

lAllNisType 仅包含 5 个对象。 有一个比较返回 0。因此,从 lAllNisType 中删除了一个对象。

我不知道这里发生了什么。 对象不同。如果我这样做:

final Set<NisType> lAllNisType = new HashSet<NisType>(pAllNisType);

lAllNisType 有 6 个元素。

感谢您的帮助

斯特凡

最佳答案

是的,其行为与 documented. 完全相同

Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal. The behavior of a sorted set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

如果 compare 返回 0,则就集合而言,两个元素被视为相等,并且集合中只能出现其中一个。如果您想保留这两个对象,则需要使比较器区分它们,例如通过二次订购。

关于java - TreeSet 中执行 Comparator 后删除的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26469102/

相关文章:

java - TreeSet:有效地元素数量小于某个值

java - 如何填充组合框

java - 如何执行 now() 查询(MYSQL)?

c++ - 使用元素的投影而不是比较器进行排序

Java:Comparable 与 Comparator - 内存和性能

c++ - 自定义比较器(排序)作为(多) map 排序参数?

java - 如何找到 Hibernate + Spring-JPA 的兼容版本对? (无法打开 JPA EntityManager 进行交易)

java - Android 创建跑马灯文字

Java - TreeSet 接受重复项

java - 在 Java 中迭代 TreeSet 比迭代 HashSet 慢吗?