removeAll(Collection c) Removes all objects from the calling collection that are in c.
retainAll(Collection c) In the collection that 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 uncommon elements, and removeAll does the action set above
With
Collection#removeAll
no more mystery, remove all items from one collection that are contained in the other. WithCollection#retainAll
is more curious. Both methods and others in this interface rely on theequals
and methodshashCode
for comparison. When you execute it willretainAll
compare the elements of both lists by means ofequals
, if it doesn't find it then it compares by reference. This is why it is important to overrideequals
if you will use this method.Therefore, it has a totally opposite operation. One removes common elements, while the other retains common elements.
Simple answer: Yes. But of course, it will depend on the concrete class (eg ArrayList) and the specific implementation.
Both methods depend on the method
contains
, which depends onindexOf
, thenequals
, which depends on the methodequals
of the contained object and therefore it makes sense that the algorithm is practically the same but with a different condition.Here you have the sources of the implementation (Open JDK) of ArrayList where you can verify what I say. If you look closely, you'll see that both methods call a third called method
batchRemove
that implements the algorithm but changes the condition.Greetings.