Java Reference
In-Depth Information
// Remove "Donna" from the list
list.remove("Donna"); // Same as list.remove(2);
System.out.println("List (after removing Donna): " + list);
}
}
List: [John, Richard, Donna, Ken]
Size of List: 4
Index=0, Element=John
Index=1, Element=Richard
Index=2, Element=Donna
Index=3, Element=Ken
Sub List 1 to 3(excluded): [Richard, Donna]
List (after removing Donna): [John, Richard, Ken]
A
List
lets you iterate over its elements using a specialized iterator represented by an instance of the
ListIterator
interface. The
ListIterator
interface inherits the
Iterator
interface; it adds a few more methods to
give you access to elements in the list from the current position in the backward direction. You can get a list iterator for
all elements of the list or a sublist, like so:
List<String> list = new ArrayList<>();
// Populate the list here...
// Get a full list iterator
ListIterator<String> fullIterator = list.listIterator();
// Get a list iterator, which will start at index 5 in the forward direction.
// You can iterate to an index that's less than 5 if you choose to.
ListIterator<String> partialIterator = list.listIterator(5);
The
hasPrevious()
method of the
ListIterator
returns
true
if there is an element before the current position
in the list iterator. To get the previous element, you need to use its
previous()
method. You can observe that the
hasPrevious()
and
previous()
methods do the same work but in the opposite direction of the
hasNext()
and
next()
methods. You can also get to the index of the next and previous element from the current position using its
nextIndex()
and
previousIndex()
methods. It also has methods to insert, replace, and remove an element at the
current location.
Listing 12-14 demonstrates how to use a
ListIterator
. It iterates over elements of a
List
, first in the forward
direction and then in the backward direction. You do not need to recreate the
ListIterator
again to iterate in the
backward direction.
Listing 12-14.
Iterating Over the Elements in a List in Forward and Backward Directions
// ListIteratorTest.java
package com.jdojo.collections;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;