简体   繁体   中英

Alternative to using TreeSet in java?

I'm looking for a Set class that will use a given comparator to removeAll().

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...

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

Long story short removeAll() uses the equals() method. (But oddly enough the remove() method doesn't...)

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

does such an animal animal exist?

TreeSet.removeAll method accepts Collection<?> as parameter. Objects in collection can be of any type, not necessarily Comparable objects. You need to make your own Set with a different method. 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.

Two object can absolutely different (equals return false) but still have the same size (think about complex numbers for example).

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.

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方法?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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