Giving your list a type
To create a list you need a type (any class, e.g. [String](<http://stackoverflow.com/documentation/java/109/strings>)
). This is the type of your List
. The List
will only store objects of the specified type. For example:
List<String> strings;
Can store "string1"
, "hello world!"
, "goodbye"
, etc, but it can’t store 9.2
, however:
List<Double> doubles;
Can store 9.2
, but not "hello world!"
.
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, which means that does not have a constructor, rather methods that a class must override. ArrayList
is the most commonly used List
, though LinkedList
is also common. So we initialise our 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 a List
variable: