The LinkedList
class is based on the linked list data structure, just as the ArrayList
class is based on the array data structure. An array is a random access data structure of contiguous elements. Any element in an array can be accessed directly using an index. In a linked list, the elements are connected by links and are not necessarily contiguous. In a linked list, the elements cannot be accessed directly; the elements must be accessed sequentially, following the links until the desired element is reached. A good analogy for an array is the viewing of a DVD (digital video disc). Any scene in a movie on a DVD can be accessed directly using the DVD scene selection menu to 'jump' to the scene.
By contrast, playing a videocassette tape is an example of a linked list. To reach a scene with a videocassette recorder/player (VCR), the tape must be advanced through all of the previous scenes. Some high-end VCRs have a feature that automatically goes back and marks the beginning and end of each commercial of a recorded program. Then, when playing the tape — with the commercial advance feature turned on — the VCR fast-forwards over the ads to skip them. To the user, it appears that the VCR is accessing the marked positions directly. However, the VCR internally sequences through the taped commercials to reach the marked positions. This is similar to what happens in a linked list when accessing an element by an index.
-
The LinkedList
class, java.util.LinkedList
, provides the following methods in addition to the List methods:
void addFirst( Object x)
void addLast(Object x)
Object getFirst()
Object getLast()
Object removeFirst()
Object removeLast()
-
To declare a reference variable for a LinkedList
, do the following.
// myLinkedList is a reference to an LinkedList
// object.
LinkedList <ClassName> myLinkedList =
new LinkedList <ClassName> ();
-
An object can be declared as a List
and created as a LinkedList
or ArrayList
. In that case, only the methods of List
are available to the object. The advantage is that either implementation can be chosen without having to change any of the code that uses the object.
if (implementationChoice.equals("LinkedList")) {
List <String> list = new LinkedList <String>();
}
if (implementationChoice.equals("ArrayList")) {
List <String> list = new ArrayList <String>();
}
list.add("John");
list.add("George");
for(String temp : list){
System.out.println(temp);
}
Notice that the for each loop can be used here. A for each loop can be used in any collection that implements Iterable.