Skip to content
Tutorials Center
My learning

Topics

Lesson 87 of 201 ยท Collections

Iterators and ListIterator

Learn Java iterators - hasNext, next and remove, ListIterator for both directions, why ConcurrentModificationException happens, and how to implement Iterable.

Every for-each loop over a collection is secretly using an iterator: a small object that walks through the elements one at a time and remembers where it is. Most of the time you never see it. But the moment you need to remove elements while looping, walk a list backward, replace elements in place, or make your own class work in a for-each loop, you need to use iterators directly.

This lesson shows what the for-each loop turns into, how Iterator and ListIterator work, why changing a collection during a loop throws ConcurrentModificationException, and how to make your own types iterable.

The Iterator interface

Iterator<E> has just three methods you'll use (plus one convenience method):

Method What it does
hasNext() true if there is at least one more element
next() returns the next element and moves past it; throws NoSuchElementException if there is none
remove() removes the element that the last next() returned (optional; some iterators don't support it)
forEachRemaining(action) runs an action on every element not yet visited

Any Collection gives you an iterator through iterator(). Think of the iterator's position as a cursor sitting between elements: next() jumps over one element and hands it to you.

Java Driving an iterator by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What for-each really does

The compiler rewrites a for-each loop over an Iterable into an iterator loop. These two are equivalent:

Java
for (String color : colors) {
    IO.println(color);
}

// what the compiler generates (roughly)
for (Iterator<String> it = colors.iterator(); it.hasNext(); ) {
    String color = it.next();
    IO.println(color);
}

For arrays, for-each becomes a plain index loop instead; arrays don't have iterators. The rewrite explains every for-each limitation from for Loops: the iterator is hidden, so you can't call its remove(), and you can't ask it for an index.

Removing elements while iterating

Here's a bug almost every Java developer writes once. You loop over a list and remove the elements you don't want:

Java Removing inside for-each fails

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The example fails on purpose. The first even number, 2, is removed, and on the next step the hidden iterator notices the list has changed and throws.

The word "concurrent" is misleading: there is only one thread here. It means "modified while being iterated". The collection keeps a modification counter (modCount) that increases on every structural change (add, remove, clear). Each iterator records the counter when it's created and checks it on every next(). If they differ, the iterator throws instead of continuing with an inconsistent view of the data. This behavior is called fail-fast.

There are two correct ways to do this:

Java Two safe ways to remove

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Iterator.remove() updates the iterator's own expected count, so the iterator stays valid. removeIf does the same job in one line, and on an ArrayList it's much faster for many removals: it shifts the remaining elements once at the end, while repeated remove calls shift the tail every time. Prefer removeIf unless you need extra logic per element.

Rules for Iterator.remove()

  • Call next() first. remove() removes the element next() just returned.
  • Call it at most once per next(). A second remove() in a row, or a remove() before any next(), throws IllegalStateException.
  • Not every iterator supports it. Iterators of List.of(...) and other unmodifiable collections throw UnsupportedOperationException.

Fail-fast is best effort

ConcurrentModificationException exists to catch bugs, not to guarantee anything. A famous quirk: removing the second-to-last element inside a for-each loop over an ArrayList does not throw at all. After the removal, the list is one shorter, so hasNext() returns false and the loop simply stops, skipping the last element without any error:

Java The bug that doesn't throw

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Never write code that relies on catching ConcurrentModificationException. Treat any change to a collection during a for-each loop as a bug, whether it throws or not. Collections built for concurrent use, such as CopyOnWriteArrayList and ConcurrentHashMap, have iterators that never throw this exception (see Concurrent Collections).

Iterating a map with an iterator

Maps aren't Iterable themselves, but their views (entrySet(), keySet(), values()) are. Iterating entrySet() lets you read keys and values together, remove entries, and even change values in place with Map.Entry.setValue:

Java Updating and removing map entries in one pass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

setValue changes a value without adding or removing an entry, so it isn't a structural modification and doesn't upset the iterator. Calling lives.put(...) with a new key in the same loop would.

ListIterator: both directions, with editing

List offers a richer iterator, ListIterator, from listIterator() or listIterator(startIndex). On top of Iterator, it can:

Method What it does
hasPrevious(), previous() move backward
nextIndex(), previousIndex() the index of the element next()/previous() would return
set(e) replace the element last returned by next() or previous()
add(e) insert an element at the cursor position
Java ListIterator set, add and walking backward

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

add inserts the new element just before the cursor, so the next call to next() returns the element that came after it. The loop doesn't visit what it just added, which prevents endless loops. Indexes always describe the list as it is now: the second "TODO" started at index 3 but reports 4, because the inserted line pushed it along. Start a ListIterator at size() and use previous() to walk backward; on Java 21 you can also loop over list.reversed() (see Immutable Collections and Utility Methods).

On a LinkedList, ListIterator.add and remove are O(1), because the iterator already holds the node. That's one of the few cases where a LinkedList beats an ArrayList.

Making your own class Iterable

Any class that implements Iterable<T> works in a for-each loop. The interface has one abstract method, iterator(). Write an iterator that tracks its position, and you're done:

Java A Range class that works with for-each

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notes on writing good iterators:

  • Each call to iterator() returns a fresh iterator, so the same Range can be looped over many times, even in nested loops.
  • next() must throw NoSuchElementException when there are no more elements, not return null or a garbage value.
  • hasNext() must not change anything. Callers may call it several times in a row.
  • remove() is optional. The interface's default throws UnsupportedOperationException, which is right for read-only data like this range.
  • The iterator here is an anonymous class (see Nested, Inner, Local and Anonymous Classes). It can read start, end and step from the enclosing record.

Implementing Iterable also gives you forEach for free. If you want stream support too, StreamSupport.stream(range.spliterator(), false) turns any Iterable into a stream.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens if you call list.remove(x) inside a for-each loop over the same ArrayList?

    The hidden iterator checks the list's modification count on each next() call and throws when the list was changed behind its back. In rare cases, like removing the second-to-last element, the loop just stops silently, which is still a bug.
  2. 2. What does this print? Iterator<Integer> it = new ArrayList<>(List.of(1, 2, 3)).iterator(); it.next(); it.remove(); it.remove();

    remove() may be called once per next(). The second call has no element to remove and throws IllegalStateException.
  3. 3. Which is the simplest correct way to delete all empty strings from an ArrayList called words?

    removeIf handles the iteration and removal safely and efficiently. The for-each version throws or skips elements, and the other two don't express the task correctly.
  4. 4. List [a, b, c]. A ListIterator calls next() (returns a) and then add("x"). What does the next call to next() return?

    add inserts x before the cursor, which is now between x and b. The following next() returns b, so the loop does not revisit the inserted element.
  5. 5. What must a class implement so that for (var item : myObject) compiles?

    for-each works on arrays and on any Iterable. Implementing Iterable means providing an iterator() method that returns a fresh Iterator.

Summary

  • An Iterator walks a collection with hasNext() and next(); next() past the end throws NoSuchElementException.
  • For-each over a collection is compiled into an iterator loop, which is why it can't remove elements or give you an index.
  • Changing a collection structurally during iteration triggers a fail-fast ConcurrentModificationException; it's best effort, so never rely on it.
  • Remove safely with Iterator.remove() (once per next()) or, more simply, removeIf, which also works on map views.
  • ListIterator moves both ways, reports indexes and can set and add during the loop.
  • Implement Iterable<T> with an iterator() that returns a fresh iterator to make your class work in for-each loops.

Next: Queues, Deques and PriorityQueue, where you'll process elements first-in-first-out, use ArrayDeque as a stack and always pull out the most important item first.