gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:24:21 29 4
gpt4 key购买 nike

我的代码很平静:

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com