Monthly Archives: October 2010

Creating and intitializing ArrayList in one line

There are multiple ways of creating a ArrayList and adding a couple of items to it. 

The usual way to do it:

List<String> normal = new ArrayList<String>();
		normal.add("one");
		normal.add("two");
		normal.add("three");

Or you could use the double braces. The inner pair of braces creates a anonymous innner class

List<String> doubleBraces = new ArrayList<String>() {{
				add("one");
				add("two");
				add("three");
		}};

But I prefer to use a small static method that uses generics and varargs to accomplish the same thing.

public class Simple {

	public static <T> ArrayList<T> listOf(T... elements) {
		ArrayList<T> list = new ArrayList<T>();
		for (T element : elements) {
			list.add(element);
		}
		return list;
	}
}

And to use it you just write:

List<String> simple = Simple.listOf("one", "two", "three");