Tuesday, April 20, 2010

Collections.addAll for adding an array of elements to a Collection

Shows there is always more that you can learn about the JRE. I have been for ages using the following idiom to add an array of items to a collection:

Collection<Foo> foos = ...;
Foo[] foosToAdd = ...;
foos.addAll(Arrays.asList(foosToAdd);

What I hadn't noticed is that the java.util.Collections class has a static method that does this:

Collection<Foo> foos = ...;
Foo[] foosToAdd = ...;
Collections.addAll(foos, foosToAdd);

Which is not only a little bit simpler but the javadoc says is faster for most implementations of Collection.

Better yet, Collections.addAll takes a variable length argument list and not just a straight array so you can do without the array declaration and just do:

Collection<Foo> foos = ...;
Collections.addAll(foos, foo1, foo2, etc);

See: Collections.addAll Javadoc