# 为什么 TreeSet 的 remove() 方法对于整数不起作用？

go评论52阅读模式

why TreeSet 's remove() method doesn't work for Integers?

# 问题

``````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.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&lt;Integer&gt; set = new TreeSet&lt;Integer&gt;( (I1,I2)-&gt;(I1 &lt; I2) ? 1 : (I1 &gt; I2) ? -1 :-1);

set.remove(new Integer(4)) ;

System.out.println( set  );

}
}
``````

# 答案1

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.

See here

> 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

``````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&lt;Integer&gt; set= new TreeSet&lt;Integer&gt;(Collections.reverseOrder()) ;
``````

• 本文由 发表于 2020年4月8日 18:25:14
• 转载请务必保留本文链接：https://go.coder-hub.com/61098453.html
• java
• treeset

go 48

go 56

go 50

go 58