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

huangapple go评论52阅读模式
英文:

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&lt;Integer&gt; set = new TreeSet&lt;Integer&gt;( (I1,I2)-&gt;(I1 &lt; I2) ? 1 : (I1 &gt; 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 接口。 (有关一致性定义的详细信息,请参见 ComparableComparator。)这是因为 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.

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

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

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

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定