为什么 TreeSet 的 remove() 方法不适用于整数?

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  );

    }
}

问题是你的比较器,你没有处理对象相等的情况(你应该 return 0)。无论如何,在你的情况下你甚至不需要显式使用自定义比较器,你可以像这样创建你的集合并且它会起作用:

TreeSet<Integer> set= new TreeSet<Integer>(Collections.reverseOrder()) ;

首先,你的 Comparator 坏了,它应该 return 0 相等的元素。

其次,TreeSet 使用 compare 查找元素,这与一般的 Set 约定相矛盾。

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.