Giving your list a type
To create a list you need a type (any class, e.g.
String). This is the type of your
List will only store objects of the specified type. For example:
"goodbye", etc, but it can't store
9.2, but not
Initialising your list
If you try to add something to the lists above you will get a NullPointerException, because
doubles both equal null!
There are two ways to initialise a list:
Option 1: Use a class that implements List
List is an interface, which means that does not have a constructor, rather methods that a class must override.
ArrayList is the most commonly used
LinkedList is also common. So we initialise our list like this:
List<String> strings = new ArrayList<String>();
List<String> strings = new LinkedList<String>();
Starting from Java SE 7, you can use a diamond operator:
List<String> strings = new ArrayList<>();
List<String> strings = new LinkedList<>();
Option 2: Use the Collections class
Collections class provides two useful methods for creating Lists without a
emptyList(): returns an empty list.
singletonList(T): creates a list of type T and adds the element specified.
And a method which uses an existing
List to fill data in:
addAll(L, T...): adds all the specified elements to the list passed as the first parameter.
import java.util.List; import java.util.Collections; List<Integer> l = Collections.emptyList(); List<Integer> l1 = Collections.singletonList(42); Collections.addAll(l1, 1, 2, 3);