英文:
why TreeSet 's remove() method doesn't work for Integers?
问题
代码运行结果为 --> [5, 4, 3],为什么 4 仍然在集合中?
public class Temp4 {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<Integer>((I1, I2) -> (I1 < I2) ? 1 : (I1 > I2) ? -1 : -1);
set.add(new Integer(5));
set.add(new Integer(3));
set.add(new Integer(4));
set.remove(new Integer(4));
System.out.println(set);
}
}
英文:
The code results this output --> [5, 4, 3],
Why 4 is still in the set ?
public class Temp4 {
public static void main (String[] args) {
TreeSet<Integer> set = new TreeSet<Integer>( (I1,I2)->(I1 < I2) ? 1 : (I1 > I2) ? -1 :-1);
set.add(new Integer(5) );
set.add(new Integer(3) );
set.add(new Integer(4) );
set.remove(new Integer(4)) ;
System.out.println( set );
}
}
答案1
得分: 2
首先,你的 Comparator
出了问题,对于相等的元素应该返回 0
。
其次,TreeSet
在查找元素时使用 compare
,与一般的 Set
接口规范相矛盾。
需要注意的是,集合维护的排序(无论是否提供了显式比较器)必须与相等操作一致,以便正确实现
Set
接口。 (有关一致性定义的详细信息,请参见Comparable
或Comparator
。)这是因为Set
接口是根据相等操作定义的,但TreeSet
实例使用其compareTo
(或compare
)方法执行所有元素比较,因此通过此方法判断为相等的两个元素在集合的观点中是相等的。 即使排序与相等性不一致,集合的行为也是定义良好的;它只是未遵守Set
接口的一般约定。
英文:
First of all, your Comparator
is broken, it should return 0
for equal elements.
Second the TreeSet
uses compare
to find elements, in contradiction to the general Set
contract.
> Note that the ordering maintained by a set (whether or not an explicit
> comparator is provided) must be consistent with equals if it is to
> correctly implement the Set interface. (See Comparable or Comparator
> 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 TreeSet instance 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 set, equal. The
> behavior of a set is well-defined even if its ordering is inconsistent
> with equals; it just fails to obey the general contract of the Set
> interface.
答案2
得分: 0
问题在于你的比较器,你没有处理对象相等的情况(应该返回0)。无论如何,在你的情况下,你甚至不需要显式地使用自定义比较器,你可以像这样创建你的集合,它会工作:
TreeSet<Integer> set = new TreeSet<Integer>(Collections.reverseOrder());
英文:
The problem is your comparator, you're not handling the cases in which the objects are equal (you should return 0). Anyway, in your case you don't even need to explicitly use a custom comparator, you can create your set like this and it will work:
TreeSet<Integer> set= new TreeSet<Integer>(Collections.reverseOrder()) ;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论