ListIterator
A ListIterator is an iterator that can move both ways on a List. It also knows the next index and can add or set at the cursor.
Detailed Explanation
Iterator only goes forward. Lists are indexed, so they can do more. list.listIterator() starts before index 0. list.listIterator(i) starts before index i. next and previous move the cursor. nextIndex and previousIndex report positions. After next, set replaces the element you just saw. add inserts before the implicit next element.
This is the API that LinkedList can implement efficiently for local edits once you have walked to the node. On ArrayList, add still shifts the tail of the array. The iterator still beats get(i) on a LinkedList because it holds the current node.
remove removes the last element returned by next or previous. You cannot remove or set until you have moved, and you cannot remove twice without another move. Fail-fast rules match Iterator: a structural change from outside throws ConcurrentModificationException.
You reach for ListIterator when you need to walk backward, when you insert while scanning (merging, rewriting a token list), or when you implement a list. You keep a plain iterator or enhanced for when you only read forward. You use indexes on ArrayList when you need random jumps; a list iterator is still sequential.
The cost of forgetting which way you last moved is an IllegalStateException on set/remove. The cost of using ListIterator on a huge LinkedList to "get the last element" is an O(n) walk; getLast exists on LinkedList and SequencedCollection. Prefer the dedicated end methods.
List.of iterators are still list iterators in type but reject add, set, and remove. Check the list you were handed.
Code Examples
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class Rewrite {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("a", "and", "b"));
ListIterator<String> it = words.listIterator();
while (it.hasNext()) {
if ("and".equals(it.next())) {
it.set("&");
}
}
System.out.println(words); // prints: [a, &, b]
}
}import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class Back {
public static void main(String[] args) {
List<Integer> xs = new ArrayList<>(List.of(1, 2, 3));
ListIterator<Integer> it = xs.listIterator(xs.size()); // past the end
while (it.hasPrevious()) {
System.out.print(it.previous());
}
// prints: 321
}
}Common Gotchas
`set`/`remove` before `next` or `previous` throws `IllegalStateException`
the cursor has no current element yet.
`add` does not make the new element the current one
a following `remove` still refers to the previously returned element rules; read the contract if you mix `add` and `remove`.
`listIterator(i)` starts at `i`, not after a `get(i)` call
`next()` then returns `list.get(i)`.
Unmodifiable lists reject `add`/`set`/`remove`
Unmodifiable lists reject `add`/`set`/`remove`