Alternative to using TreeSet in java?

I am looking for a Set class that will use this comparator for removeAll ().

I used TreeSet, but after a few hours tore my hair, trying to understand why my removeAll () does not remove everything I found ...

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

In short, removeAll () uses the equals () method. (But, oddly enough, the remove () method is not ...)

I need a set in which duplicates are removed, preferably using a comparator, but not required, and I cannot override the equals b / c method. I need this, as for other logic. And, obviously, I would like to avoid creating a loop that calls remove () for all elements so that it doesn't confuse me in the future (or anyone else).

Does such an animal exist?

+4
source share
4 answers

TreeSet.removeAllthe method accepts Collection<?>as a parameter. Objects in a collection can be of any type, not necessarily comparable objects. You need to make your own set using another method. Please note that the resolution of the error "will not be fixed"

0
source

The behavior is actually very believable. 'equals' determines whether two objects have the same identifier, and comparison determines the relationship between some form of size that is addressed to them.

Two objects can be completely different (equal to false false), but still have the same size (for example, about complex numbers).

, removeAll , ( ), , , , .

, : -)

0

you can 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);
}
0
source

Do you override the equals and hashcode methods of the object contained in the TreeSet?

0
source

Source: https://habr.com/ru/post/1525563/


All Articles