Lists – Collections: Part II
15.3 Lists
Lists are collections that maintain their elements in order and can contain duplicates. The elements in a list are ordered. Each element, therefore, has a position in the list. A zero-based index can be used to access the element at the position designated by the index value. The position of an element can change as elements are inserted or deleted from the list—that is, as the list is changed structurally.
The List<E> Interface
In addition to the operations inherited from the Collection<E> interface, the List<E> interface also defines operations that work specifically on lists: position-based access of the list elements, searching in a list, operations on parts of a list (called open range-view operations), and applying an operator to each element. These list operations are covered in Chapter 12, p. 643.
Sorting and searching in lists is covered in §15.11, p. 856.
The List<E> interface also provides the overloaded static method of() to create unmodifiable lists (§12.2, p. 649).
Additionally, the List<E> interface provides two customized list iterators:
ListIterator<E> listIterator()
ListIterator<E> listIterator(int index)
The iterator from the first method iterates over the elements consecutively, starting with the first element of the list, whereas the iterator from the second method starts iterating over the list from the element designated by the specified index.
The declaration of the ListIterator<E> interface is shown below:
interface ListIterator<E> extends Iterator<E> {
boolean hasNext();
boolean hasPrevious();
E next(); // Element after the cursor
E previous(); // Element before the cursor
int nextIndex(); // Index of element after the cursor
int previousIndex(); // Index of element before the cursor
void remove(); // Optional
void set(E o); // Optional
void add(E o); // Optional
}
The ListIterator<E> interface is a bidirectional iterator for lists. It extends the Iterator<E> interface and allows the list to be iterated over in either direction. When iterating over lists, it can be helpful to imagine a cursor moving forward or backward between the elements when calls are made to the next() and the previous() methods, respectively. The element that the cursor passes over is returned. When the remove() method is called, the element last passed over is removed from the list.