As with Java collections generally, there isn't actually a single Java class called
List1. Instead, there is an interface called List,
with various implementations. So a typical way to create a list would
look like this:
import java.util.*;
List<String> myList = new ArrayList<String>();
In the above example, we import all classes from java.util, which is
where List and ArrayList reside. Unless
otherwise stated, assume that all of the collections classes we mention from now on
are in the java.util package, and you will need to import them.
In this example, the actual collection object that we create is an ArrayList.
This is a list implementation that stores objects inside an array. Although arrays have
to be fixed-size, ArrayList internally handles this by creating a new, bigger
array where necessary and copying the previous elements into the new array. So to the
caller, what we effectively get is a list with no fixed size which we can add to and
remove from arbitrarily.
Notice that we also state, inside angle brackets, that the list will specifically
hold objects of type String. If you haven't come across it before, this
syntax was introduced in Java 5, part of what is technically called the generics
framework; we'll introduce more details as we go along.
Now we have our list, we can start doing interesting things with it such as
adding and removing elements. Any List
provides various methods, including add(), get(), size():
myList.add("Hello");
myList.add("world");
System.out.println("The list contains " +
myList.size() + "elements, and " +
"the first is " + myList.get(0));
|
Interfaces
A key feature of Java used in the collections framework is the notion of
interfaces and implementations. An interface
is a "blueprint" for a class: it specifies a series of methods, but does not
contain any code inside those methods. For example, the List
interface includes the methods add() and size(). This means that
any class that wants to be a list implementation must include an add() and a size() method,
but doesn't state how individual classes should implement these methods (i.e. what code
goes in the method). That's up to individual classes. For example, the ArrayList class
implements its add() method by putting the object in its underlying array.
The LinkedList class implements its add() method by adding the object
to the end of its linked 'chain of objects'. The advantage of having interfaces is that
we can write code that is more 'general': we can write
code that operates on "any sort of list", always referring to the object in question
as a List (the name of the interface), without having to worry about whether it's
specifically an ArrayList or a LinkedList that we're dealing with
in any one case.
For more information, see the separate section on interfaces in Java.
|