Creating a List
suggest changeGiving your list a type
To create a list you need an element type (any reference type, for example String). The List stores only objects of that type. For example:
List<String> strings;
It can store "string1", "hello world!", "goodbye", and so on, but it cannot store 9.2:
List<Double> doubles;
It can store 9.2, but not "hello world!". 9.2 is boxed to Double.
Initialising your list
If you try to add something to the lists above you will get a NullPointerException, because strings and doubles both equal null!
There are two ways to initialise a list:
Option 1: Use a class that implements List
List is an interface, so it has no constructor. A class such as ArrayList implements its methods. ArrayList is the most commonly used List, though LinkedList is also common. Initialise the list like this:
List<String> strings = new ArrayList<String>();
or
List<String> strings = new LinkedList<String>();
Starting from Java SE 7, you can use a diamond operator:
List<String> strings = new ArrayList<>();
or
List<String> strings = new LinkedList<>();
Option 2: Use the Collections class
The Collections class provides two useful methods for creating lists without calling a List constructor:
emptyList(): returns an empty immutable list.singletonList(T): returns an immutable list containing the specified element.
addAll fills an existing mutable collection:
addAll(Collection<? super T>, T...): adds the specified elements to the collection passed as the first parameter.emptyList()andsingletonList()do not support it and throwUnsupportedOperationException.
Examples:
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
List<Integer> l = Collections.emptyList();
List<Integer> l1 = Collections.singletonList(42);
List<Integer> l2 = new ArrayList<Integer>();
Collections.addAll(l2, 1, 2, 3);