简体   繁体   English

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

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

The code results this output --> [5, 4, 3], Why 4 is still in the set?代码结果是这个output --> [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  );

    }
}

First of all, your Comparator is broken, it should return 0 for equal elements.首先,你的Comparator坏了,它应该为相等的元素返回0

Second the TreeSet uses compare to find elements, in contradiction to the general Set contract.其次, 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.请注意,如果要正确实现 Set 接口,集合维护的顺序(无论是否提供显式比较器)必须与 equals 一致。 (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. (有关与等于一致的精确定义,请参阅 Comparable 或 Comparator。)之所以如此,是因为 Set 接口是根据 equals 操作定义的,但 TreeSet 实例使用其 compareTo(或比较)方法执行所有元素比较,因此两个从集合的角度来看,通过此方法被视为相等的元素是相等的。 The behavior of a set is well-defined even if its ordering is inconsistent with equals;集合的行为是明确定义的,即使它的顺序与 equals 不一致; it just fails to obey the general contract of the Set interface.它只是不遵守 Set 接口的一般合同。

The problem is your comparator, you're not handling the cases in which the objects are equal (you should return 0).问题是你的比较器,你没有处理对象相等的情况(你应该返回 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()) ;

The code results this output --> [5, 4, 3], Why 4 is still in the set?代码结果这个 output --> [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  );

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM