In Java, listIterator() returns a ListIterator, an iterator for lists that can move in both directions. Besides next() and remove(), it has hasPrevious(), previous(), add(e) and set(e).
Think of the iterator as a cursor that sits between two elements. next() jumps over the element on the right, and previous() jumps over the element on the left. The version listIterator(index) places the cursor before the element at index.
An instance method of java.util.LinkedList (since Java 1.2): call it on a LinkedList object. Add import java.util.LinkedList; at the top of your file. It is declared by List, and LinkedList implements it.
Syntax
Use the no-argument form to start at the front, or give an index.
Java
LinkedList<String> list = new LinkedList<>(Arrays.asList("A", "B", "C"));
ListIterator<String> it = list.listIterator(); // cursor before "A"
ListIterator<String> end = list.listIterator(list.size()); // cursor after "C"
String s = end.previous(); // "C"
Call
What it does
list.listIterator()
Starts at the front (index 0).
list.listIterator(index)
Starts before the element at index. Valid from 0 to size().
it.previous()
Returns the element on the left and moves back.
it.add(e) / it.set(e)
Insert a new element at the cursor, or replace the last returned element.
nextIndex() is the index that next() would return, and previousIndex() is one less.
Library declarations
Java
// java.util.LinkedList
public ListIterator<E> listIterator()
public ListIterator<E> listIterator(int index)
Parameters
Parameter
Description
index (int)
Optional. The index of the first element that next() will return. Must be between 0 and size().
Return Value
Return Value
Description
ListIterator<E>
A list iterator positioned before the element at the given index.