What is the difference between Iterator and ListIterator?
Quick Answer
Iterator supports forward-only traversal with hasNext()/next()/remove() and works on any Collection. ListIterator (List-only) additionally supports backward traversal (hasPrevious()/previous()), obtaining the current index, and in-place modification via set() and add() during iteration.
Detailed Answer
Both let you traverse a collection safely (i.e., without triggering a ConcurrentModificationException from structural changes made outside the iterator), but ListIterator is strictly more capable — and only available on Lists:
Iterator<E> | ListIterator<E> | |
|---|---|---|
| Available on | any Collection | only List |
| Direction | forward only | forward and backward |
remove() | yes | yes |
set(E) — replace last returned element | no | yes |
add(E) — insert during iteration | no | yes |
Index access (nextIndex()/previousIndex()) | no | yes |
List<String> names = new ArrayList<>(List.of("a", "b", "c"));
ListIterator<String> it = names.listIterator();
while (it.hasNext()) {
String s = it.next();
if (s.equals("b")) it.set("B"); // safe in-place modification
}
Both are the safe way to remove/modify elements while iterating — calling list.remove(x) directly inside a for-each loop throws ConcurrentModificationException; calling iterator.remove() (or listIterator.set/add) is explicitly supported because the iterator updates its own internal state to match.