Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does ArrayList.removeAll(Collection<>) cares about duplicates?

Lets say I define a list:

List<String> cards = new ArrayList<>();
cards.add("king");
cards.add("queen");
cards.add("king");
cards.add("king");
cards.add("prince");
cards.add("queen");
cards.add("prince");

So this ArrayList has 3 "king" String objects, 2 "queen", and 2 "prince". So far so good.

Now I want to define a new list:

List<String> toRemove = new ArrayList<>();
toRemove.add("king");
toRemove.add("king");
toRemove.add("queen");
toRemove.add("queen");
toRemove.add("prince");

So this ArrayList has 2 "king", 2 "queen", and 1 "prince". Now, if I will do:

cards.removeAll(toRemove);

Will this take duplicate objects into account?

If you subtract the toRemove list from the cards list, you should be left with 1 "king", 0 "queen", and 1 "prince". Right?

But will the removeAll function recognize there are duplicate objects there, and not try to remove all occurrences of "king", "queen", and "prince" from cards, so I will be left with an empty list(cards)?

will the final list be {"king", "prince"} or an empty list {} ?

like image 824
עומר אנגי Avatar asked Jun 03 '26 08:06

עומר אנגי


1 Answers

As stated in the Java docs:

removeAll(Collection c)

Removes all of this collection's elements that are also contained in the specified collection (optional operation). After this call returns, this collection will contain no elements in common with the specified collection.

like image 174
Petar Bivolarski Avatar answered Jun 05 '26 22:06

Petar Bivolarski