What is the difference between Iterator and ListIterator?

6 minbeginneriteratorlistiteratorcollections

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 onany Collectiononly List
Directionforward onlyforward and backward
remove()yesyes
set(E) — replace last returned elementnoyes
add(E) — insert during iterationnoyes
Index access (nextIndex()/previousIndex())noyes
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.