Creating and intitializing ArrayList in one line

By | 2010-10-10

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");

 

 

 

 

 

 

 

One thought on “Creating and intitializing ArrayList in one line

  1. GordonLiddy

    Nice blog! Will be interesting to follow. Keep up the good w0rk! :)

    Reply

Leave a Reply to GordonLiddy Cancel reply

Your email address will not be published. Required fields are marked *