Java Reference
In-Depth Information
667
Figure 1
Inserting an Element into a Linked List
The Java library provides a linked list class. In this section you will learn how to use
the library class. In the next section you will peek under the hood and see how some
of its key methods are implemented.
The LinkedList class in the java.util package is a generic class, just like the
ArrayList class. That is, you specify the type of the list elements in angle
brackets, such as LinkedList<String> or LinkedList<Product> .
The following methods give you direct access to the first and the last element in the
list. Here, E is the element type of LinkedList<E> .
void addFirst(E element)
void addLast(E element)
E getFirst()
E getLast()
E removeFirst()
E removeLast()
How do you add and remove elements in the middle of the list? The list will not give
you references to the nodes. If you had direct access to them and somehow messed
them up, you would break the linked list. As you will see in the next section, where
you implement some of the linked list operations yourself, keeping all links between
nodes intact is not trivial.
You use a list iterator to access elements inside a linked list.
Search WWH ::




Custom Search