Tuesday, April 16, 2013

4 Ways to Initialize a List in Java

Creating a List and populating it with a set of elements is a common programming task in Java. In this blog post, I'm going to describe four ways to do this.

1. Collections.emptyList()

This method will return a List object that is empty. This is a convenient, shorthand alternative to explicitly instantiating a new List object. However, this list is immutable, which means that you cannot add any elements to it.

List<String> list = Collections.emptyList();

2. Arrays.asList()

This method takes an array and converts it to a List object. What makes this method special is the fact that the argument to this method is a vararg. This means that you can pass as many elements into the method as you like. The syntax is very compact because all of the elements can fit on one line.

But note that, just as with Collections.emptyList(), the list that is created is immutable, so you cannot add or remove elements to/from it.

List<String> list = Arrays.asList("one", "two", "three");

3. Anonymous child class

A somewhat trickier way of creating a list is to define your list as an anonymous, child class. The elements are added to the list by calling the add() method within the class' initializer block (notice the double braces).

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

4. JUST CALL add(), EINSTEIN!

Of course, the traditional way to create a list is to instantiate it and then call the add() method for each element. But where's the fun in that?

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

7 comments:

Jason said...

Haven't really worked with them myself, but apparently Google Collections offer some cool utilities that let you do things like: List groceryItems2 = Lists.newArrayList("toothpaste", "soap", "cereals"); http://thoughtfuljava.blogspot.com/2012/10/concise-collection-initialization-using.html

Anonymous said...

You can also use the overloaded += operator to add an element to the list -

list += "four";

Anonymous said...

Uh.. no you cant..

Rosen Rose said...
This comment has been removed by a blog administrator.
Anonymous said...

which one is the best way to initialize the list??

Anonymous said...

I think Arrays.asList() + Copy Constructor is best way to initialize ArrayList inline in Java.

Geetha Devi said...
This comment has been removed by a blog administrator.