Iterator vs ListIterator
Walk a collection by hand when for-each is not enough, forwards or backwards.
Open this lesson in the learning hubKey points
- Every
Iterablehands out anIterator:hasNext,next, and a saferemove. - A for-each loop is an iterator. The compiler writes those same three calls for you.
ListIteratorexists on lists only. It addsprevious,set,add, and index access.setreplaces the element you just returned.addinserts before the cursor, so the walk skips it.- To go backwards start at
list.listIterator(list.size())and loop whilehasPrevious(). - Call
next()beforeremove()or you get anIllegalStateException.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("ann", "bob", "cyd", "dee"));
Iterator<String> it = names.iterator();
while (it.hasNext()) {
if (it.next().startsWith("b")) it.remove();
}
System.out.println("Iterator.remove : " + names);
ListIterator<String> li = names.listIterator();
while (li.hasNext()) {
int i = li.nextIndex();
String v = li.next();
li.set(i + ":" + v.toUpperCase());
}
System.out.println("ListIterator.set : " + names);
li = names.listIterator();
li.next();
li.add("inserted");
System.out.println("ListIterator.add : " + names);
StringBuilder backwards = new StringBuilder();
ListIterator<String> rev = names.listIterator(names.size());
while (rev.hasPrevious()) backwards.append(rev.previous()).append(" ");
System.out.println("hasPrevious walk : " + backwards.toString().trim());
System.out.println("Iterator gives you: hasNext, next, remove");
System.out.println("ListIterator adds : set, add, previous, indexes - lists only");
}
}
Iterator for any collection, ListIterator when you need to look back or edit in place.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.