Wednesday, November 23, 2005

Concise Java Collection Syntax with varargs

Here's some utility methods that makes declaring and initializing Collections in Java 5 more concise. Note that this does not make sense to use for Collections that contain a lot of items. Here's the utility methods.


public static <T> List<T> newArrayList(T... elems) {
List<t> newList = new ArrayList<T>(elems.length);
fillCollection(newList, elems);
return newList;
}

public static <T> List<T> newLinkedList(T... elems) {
List<T> newList = new LinkedList<T>(elems.length);
fillCollection(newList, elems);
return newList;
}

private static <T> void fillCollection(Collection<T> coll, T... elems) {
for (T elem : elems) {
coll.add(elem);
}
}

...



So code that looked like this before:


List<String> programmingLanguages = new ArrayList<String>(3);
programmingLanguages.add("Java");
programmingLanguages.add("C++");
programmingLanguages.add("Ruby");




Now looks like this:


List<String> programmingLanguages = CollectionUtils.newList(
"Java", "C++", "Ruby");