Initialize list

This example will show how to initialize an ArrayList using various techniques found in java and guava.

Straight up Java

List.add

This is a standard way to initialize an array list in JDK 5.0 and above.

@Test
public void initialize_list_java() {
    List<String> cheeses = new ArrayList<String>();
    cheeses.add("Munster");
    cheeses.add("Swiss");
    cheeses.add("Sharp cheddar");

    assertEquals(3, cheeses.size());
}

Diamond operator

Java 7 introduced the diamond operator which reduces java's verbosity on having to specify a generic type. The compiler will infer the parameter type based on the constructor's generic class. The snippet below will show how to initilize a ArrayList using the diamond operator.

@Test
public void initialize_list_java_diamond_operator () {

    List<String> cheeses = new ArrayList<>();
    cheeses.add("Munster");
    cheeses.add("Swiss");
    cheeses.add("Sharp cheddar");

    assertEquals(3, cheeses.size());
}

Double brace initialization

Using double brace initialization is probably more controversial as it creates an anonymous inner classes and should be used judiciously.

@Test
public void initialize_list_java_with_double_brace_initialziation () {

    @SuppressWarnings("serial")
    ArrayList<String> cheeses = new ArrayList<String>() {
        {
            add("Munster");
            add("Swiss");
            add("Sharp cheddar");
        }
    };

    assertEquals(3, cheeses.size());
}

Arrays.asList

This snippet will demonstrate initializing an ArrayList or converting an array to a ArrayList using Arrays utility.

@Test
public void initialize_list_java_with_arrays () {

    List<String> cheeses = Arrays.asList("Munster",
            "Swiss", "Sharp cheddar");

    assertEquals(3, cheeses.size());
}

Google Guava

Guava Lists.newArrayList will initialize and fill the ArrayList with the provided elements.

@Test
public void initialize_list_with_guava() {

    List<String> cheeses = Lists.newArrayList("Munster", "Swiss",
            "Sharp cheddar");

    assertEquals(3, cheeses.size());
}