4

I found next code in official java docs:

collection.removeAll(Collections.singleton(element));

I couldn't figure out advantages of this approach. Why not usual element removing?

collection.remove(element);

Thanks!

0

4 Answers 4

8

The former removes all occurrences of the element within collection, the latter removes only first occurrence.

1
  • Oh, it's pretty simple! Thank you!
    – bsiamionau
    Feb 7, 2013 at 12:26
5

Acc. to docs:

consider the following idiom to remove all instances of a specified element, e, from a Collection, c

collection.removeAll(Collections.singleton(element));

while collection.remove(element); removes a single instance of the specified element from this collection

So, to remove all instances, you've to use a loop construct with latter approach. while with first one it's just one line job.

3

From the API

remove(Object o)
Removes a single instance of the specified element from this collection, if it is present

and:

removeAll(Collection c)
Removes all of this collection's elements that are also contained in the specified collection

So, if your collection has more than one occurance of the element you wish to remove, you would have to execute collection.remove(element) several times, but removeAll only once. As removeAll takes a collection as argument, Collection.singleton can offer you a convenient way to create a collection with only one argument.

0

When testing(unit testing). Collections.singleton is a one line way to turn your subject into a collection. The alternative is two lines and not onerous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.