Varargs Collection Factory Method

One of the JavaIdioms.

As described in DoubleBraceInitialization, the JavaLanguage has no literal syntax for collections, so creating a collection takes a lot more code, and code that is a lot more stateful, than other languages. You can get around that for sets and lists by writing descriptive factory methods that take a variable number of arguments.

E.g. instead of:

 Set<String> fruit = new HashSet<String>();
you can write a factory method like this:

 <T> Set<T> setOf(T... things) {
     return new HashSet<T>(Arrays.asList(things));
And use it like this:

 doSomethingWith(setOf("banana", "pear", "apple"));

Vararg methods are only supported in Java 5 and above. If you can't use Java 5, consider DoubleBraceInitialization, as an alternative.

How about this for a more generic version?

 <T> T populateCollection(Collection<T> c, T... things) {
     return c;

populateCollection(new ArrayList<String>(), "Meh", "Mlah", "Hmm");
Avoids having to redo basically the same code for all the various types of Collection you might want to use. OnceAndOnlyOnce and all that...

-- JamesHollidge

Yes, but it doesn't read nearly as well at the call site, which is the whole point. The number of calls should be large enough compared to the number of factory methods to amortize the overhead of the extra code.

Just wondering, if Arrays.asList() uses a backing array, are there any performance or other implications to that?

- Don't necessarily quote me, but I'm fairly sure Arrays.asList() wraps the implicit varargs array. Your only substantial overhead would be the potential allocation associated with the List proxy.

View edit of January 21, 2014 or FindPage with title or text search