Do they work the same removeAll and retainAll in the Collections interface?

3

removeAll (Collection c) Delete all objects in the collection that are in c.

retainAll (Collection c) In the collection that it invokes, only those objects that are in c (intersection) will remain.

My question is, do they work the same way? Since retainAll has to remove the uncommon elements, and removeAll does the previously set action

    
asked by RoyalUp 15.06.2016 в 13:50
source

2 answers

1

With Collection#removeAll there is no greater mystery, it eliminates all the elements of a collection that are contained in the other. With Collection#retainAll it's more curious. Both methods and others in this interface rely on the methods equals and hashCode for the comparison. When you run retainAll , compare the elements of both lists by equals , if you can not find it then compare by reference. That's why it's important to overwrite equals if you'll use this method.

Therefore, it has a totally opposite operation. One eliminates common elements, while the other retains the common elements.

    
answered by 15.06.2016 / 14:13
source
0

Simple answer: Yes. But of course, it will depend on the specific class (eg ArrayList) and the specific implementation.

Both methods depend on the contains method, which depends on indexOf , then equals , which depends on the equals method of the contained object and therefore it makes sense that the algorithm is practically the same but with different condition.

Here you have the sources of the implementation (Open JDK) of ArrayList where you can see what I say. If you look closely, you will see that both methods invoke a third method called batchRemove that implements the algorithm but changes the condition.

Greetings.

    
answered by 15.06.2016 в 14:14