简体   繁体   English

在java中使用TreeSet的替代方法?

[英]Alternative to using TreeSet in java?

I'm looking for a Set class that will use a given comparator to removeAll(). 我正在寻找一个将使用给定比较器删除All()的Set类。

I was using TreeSet but after a few hours ripping my hair out trying to figured out why my removeAll() was not removing any I found this... 我正在使用TreeSet,但几个小时后我的头发试图弄清楚为什么我的removeAll()没有删除任何我发现这...

http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4730113 http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4730113

Long story short removeAll() uses the equals() method. 长话短说removeAll()使用equals()方法。 (But oddly enough the remove() method doesn't...) (但奇怪的是remove()方法不...)

I do want a Set where so duplicates are removed, preferably with the comparator but not required, and I can't override the equals method b/c I need it as is for other logic. 我确实需要一个Set,其中重复删除,最好是使用比较器,但不是必需的,我不能覆盖equals方法b / c我需要它作为其他逻辑。 And obviously I would like to avoid making a loop that calls remove() on all elements so that it doesn't confuse me in the future (or someone else). 显然我想避免在所有元素上创建一个调用remove()的循环,这样它就不会在将来(或其他人)混淆我。

does such an animal animal exist? 这样的动物动物存在吗?

TreeSet.removeAll method accepts Collection<?> as parameter. TreeSet.removeAll方法接受Collection<?>作为参数。 Objects in collection can be of any type, not necessarily Comparable objects. 集合中的对象可以是任何类型,不一定是Comparable对象。 You need to make your own Set with a different method. 您需要使用不同的方法创建自己的Set。 Note that the bug resolution is "won't fix" 请注意,错误解决方案是“无法修复”

The behavior is actually very plausible. 这种行为实际上非常合理。 'equals' determines whether two objects have the same identity, compare determines relations between some form of size that is addressed to them. 'equals'确定两个对象是否具有相同的标识,compare比较确定了与它们对应的某种形式的大小之间的关系。

Two object can absolutely different (equals return false) but still have the same size (think about complex numbers for example). 两个对象可以绝对不同(等于返回false)但仍然具有相同的大小(例如,考虑复数)。

Your expectation is that removeAll will determine what needs to be removed according to the object's 'size' (as defined by compare), what you see is that removal actually works according to identity. 您的期望是removeAll将根据对象的“大小”(由比较定义)确定需要删除的内容,您看到的删除实际上是根据身份进行的。

In short, use a loop :-) 简而言之,使用循环:-)

You may use 你可以用

public static <T> void removeAll(TreeSet<T> set, Collection<T> toRemove)
{
  TreeSet<T> toRemoveTreeSet=new TreeSet<>(set.comparator());
  toRemoveTreeSet.addAll(toRemove);
  set.removeAll(toRemoveTreeSet);
}

or 要么

public static <T> void removeAll(TreeSet<T> set, Collection<?> toRemove)
{
  for(Object o:toRemove) set.remove(o);
}

您是否重写了TreeSet包含的对象的equals和hashcode方法?

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

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