ListIterator Example in Java
Problem
ListIterator extends the plain Iterator with the ability to move backward as well as forward, and to replace the current element in place — capabilities a plain Iterator doesn't offer at all.
Given a list of colors, walk forward replacing one element, then walk the same iterator backward to confirm the change.
Java Program
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class ListIteratorDemo {
public static void main(String[] args) {
List<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
ListIterator<String> it = colors.listIterator();
while (it.hasNext()) {
String color = it.next();
if (color.equals("Green")) {
it.set("Yellow"); // replaces the just-returned element in place
}
}
System.out.println("Forward pass result: " + colors);
StringBuilder reversed = new StringBuilder();
while (it.hasPrevious()) {
reversed.append(it.previous()).append(" ");
}
System.out.println("Backward: " + reversed.toString().trim());
}
}Output
Core Logic
Walking forward with next() to find and replace one element with set(), then reusing the same iterator's hasPrevious()/previous() to walk back over the now-updated list, shows both directions working through one shared cursor.
- 1
colors.listIterator()returns aListIterator<String>, positioned before the first element, same starting point as a plain Iterator. - 2
it.next()advances forward and returns each element in turn — when it returns"Green",it.set("Yellow")replaces that element in the list without needing an index. - 3Once
hasNext()is false, the cursor sits after the last element —hasPrevious()is now true, so the same iterator can walk backward from there. - 4
it.previous()moves backward one step at a time, returning each element in reverse order, starting from the last one.
Green with Yellow, leaving [Red, Yellow, Blue]; the backward pass over that same updated list then visits Blue, Yellow, Red, in that order.Key Point: A plain Iterator only ever moves forward and can only remove — set() and previous() are exactly what ListIterator adds on top of it, and both only work on List implementations, not every Collection.
Why: Each element is visited once moving forward and once moving backward, and next()/previous()/set() are all O(1) on an ArrayList since they only read or overwrite a single array slot — unlike remove(), which needs to shift elements.