Iterator vs ListIterator
Both walk through elements and let you change the collection safely while iterating.
- Iterator works with every collection. Methods:
hasNext(),next(),remove()and (Java 8)forEachRemaining(). Forward only. - ListIterator extends Iterator and works only with lists (
list.listIterator(), orlistIterator(index)to start in the middle). It adds: - both directions:
hasPrevious()andprevious(); - positions:
nextIndex()andpreviousIndex(); - changes:
set(e)replaces the last returned element,add(e)inserts at the current position.
Use a for-each loop to just read, an Iterator to remove while looping (or simply removeIf), and a ListIterator to replace, insert or walk backwards.
Side by side
| Iterator | ListIterator | |
|---|---|---|
| Works with | Any Collection | Lists only |
| Direction | Forward | Forward and backward |
| Start position | The beginning | Anywhere: listIterator(index) |
| Remove | remove() | remove() |
| Replace | No | set(e) |
| Insert | No | add(e) |
| Index | No | nextIndex(), previousIndex() |
Example
List<String> names = new ArrayList<>(List.of("asha", "ravi", "meera"));
Iterator<String> it = names.iterator();
while (it.hasNext()) {
if (it.next().startsWith("r")) it.remove(); // safe removal while iterating
}
ListIterator<String> li = names.listIterator();
while (li.hasNext()) {
String n = li.next();
li.set(n.substring(0, 1).toUpperCase() + n.substring(1)); // replace in place: Asha, Meera
if (n.equals("asha")) li.add("Kiran"); // insert after Asha
}
System.out.println(names); // [Asha, Kiran, Meera]
while (li.hasPrevious()) System.out.print(li.previous() + " "); // Meera Kiran AshaCommon mistake
Calling list.remove(x) inside a for-each loop over the same list. Use iterator.remove() or list.removeIf(...).
Under the hood
remove() and set() act on the element most recently returned by next() or previous(); calling them before next(), twice in a row, or set() after add() throws IllegalStateException. Changing the list directly (not through the iterator) during iteration throws ConcurrentModificationException on the next step (see "Fail-fast vs fail-safe").
Check yourself
Which method is available on ListIterator but not on Iterator?
How this connects
Know these first
Where this leads
You've reached the end of this thread. Try a learning path for what's next.
Part of Java 8 and collections, practically.
Was this lesson helpful?
Finished reading? Mark it complete to track your progress.