Iterable and Iterator

Any class that implements Iterable can be used in a for-each loop, and it needs only one method: iterator(). This page explains what the compiler turns a for-each loop into and what the Iterator contract requires, then builds a range, a fail-fast collection, a lazy tree walk and an infinite sequence turned into a stream, shows the JDK's own iterator traps, and measures index loops against iterators.

Contents

What a for-each loop really does

The enhanced for loop (Java 5) works on two kinds of thing: arrays and objects that implement java.lang.Iterable. For an array, the compiler generates an index loop. For an Iterable, it generates this:

  1. Call iterable.iterator() once to get a fresh Iterator.
  2. Loop while hasNext() returns true, calling next() to get each element.

So for (T x : items) is exactly for (Iterator<T> it = items.iterator(); it.hasNext(); ) { T x = it.next(); ... }. Making your own class iterable means implementing that one method well. The Iterator contract has a few rules that the JDK classes follow and callers rely on:

  • hasNext() must have no visible side effects: calling it twice in a row must give the same answer and must not skip an element.
  • next() must throw NoSuchElementException when there are no more elements, not return null.
  • remove() is optional. Since Java 8 its default implementation throws UnsupportedOperationException; when supported, it removes the element last returned by next() and may be called once per next().
  • iterator() should return a new, independent iterator on every call, so the same object can be looped over again and by two loops at once.
The iteration interfaces
InterfaceSinceAddsBest for
EnumerationJava 1.0hasMoreElements, nextElementOld APIs only (Vector, Hashtable); asIterator() converts it (Java 9)
IteratorJava 1.2hasNext, next, optional remove, forEachRemaining (Java 8)Walking any sequence one element at a time
ListIteratorJava 1.2Backwards movement, set, add, indexesEditing a list in place while walking it
IterableJava 5iterator(); forEach and spliterator defaults (Java 8)Anything usable in for-each
SpliteratorJava 8Splitting for parallelism, characteristics, size estimatesFeeding streams
PrimitiveIterator.OfInt and friendsJava 8nextInt() without boxingIterating primitive sequences

The programs below were run on JDK 21.

A custom Iterable: a numeric range

A range from 0 to 10 in steps of 2 is the smallest useful Iterable. The program loops over it twice to show that each loop gets a new iterator, then runs past the end on purpose.

Java
import java.util.Iterator;
import java.util.NoSuchElementException;

// A custom range that works in for-each loops
public class RangeIterable implements Iterable<Integer> {

    private final int start;
    private final int end;      // exclusive
    private final int step;

    RangeIterable(int start, int end, int step) {
        this.start = start;
        this.end = end;
        this.step = step;
    }

    @Override
    public Iterator<Integer> iterator() {          // a NEW iterator each time
        return new Iterator<>() {
            private int next = start;

            @Override
            public boolean hasNext() {
                return next < end;
            }

            @Override
            public Integer next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                int value = next;
                next += step;
                return value;
            }
        };
    }

    public static void main(String[] args) {
        RangeIterable evens = new RangeIterable(0, 10, 2);
        for (int n : evens) {                       // the compiler calls iterator()
            System.out.print(n + " ");
        }
        System.out.println();
        for (int n : evens) {                       // works again: fresh iterator
            System.out.print(n * 10 + " ");
        }
        System.out.println();

        Iterator<Integer> it = evens.iterator();
        while (it.hasNext()) {
            it.next();
        }
        try {
            it.next();
        } catch (NoSuchElementException e) {
            System.out.println("next() after the end: NoSuchElementException");
        }
        evens.forEach(n -> System.out.print("[" + n + "]"));    // default method on Iterable
        System.out.println();
    }
}

Output:

Output
0 2 4 6 8 
0 20 40 60 80 
next() after the end: NoSuchElementException
[0][2][4][6][8]
  • The second loop printed the full range again, multiplied by 10, because iterator() creates a new anonymous iterator with its own next field each time. The range object itself holds no iteration state.
  • Calling next() after the last element threw NoSuchElementException, as the contract requires. next() calls hasNext() itself, so a caller that skips the check still gets the right exception.
  • forEach came for free: it is a default method of Iterable (Java 8) that runs the same loop with a lambda.
  • The range yields Integer objects, so every element is boxed. For a hot numeric loop, implement PrimitiveIterator.OfInt, or just use IntStream.range.

A collection with a fail-fast iterator

The JDK collections detect most changes made behind an iterator's back with a counter called modCount: every structural change increments it, and each iterator remembers the value it started with. The small bag below implements the same scheme, including remove(), and is given words of length 1 and 2 so that the iterator can remove the two-letter ones.

Java
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;

// A tiny growable collection with a fail-fast iterator that supports remove()
public class FailFastBag<T> implements Iterable<T> {

    private Object[] items = new Object[4];
    private int size;
    private int modCount;                         // bumped on every structural change

    void add(T item) {
        if (size == items.length) {
            items = Arrays.copyOf(items, size * 2);
        }
        items[size++] = item;
        modCount++;
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<>() {
            private int cursor;
            private int lastReturned = -1;
            private int expectedModCount = modCount;

            @Override
            public boolean hasNext() {
                return cursor < size;
            }

            @Override
            @SuppressWarnings("unchecked")
            public T next() {
                checkForChanges();
                if (cursor >= size) {
                    throw new NoSuchElementException();
                }
                lastReturned = cursor;
                return (T) items[cursor++];
            }

            @Override
            public void remove() {
                if (lastReturned < 0) {
                    throw new IllegalStateException("next() not called");
                }
                checkForChanges();
                int moved = size - lastReturned - 1;
                System.arraycopy(items, lastReturned + 1, items, lastReturned, moved);
                items[--size] = null;
                cursor = lastReturned;
                lastReturned = -1;
                expectedModCount = ++modCount;     // our own change is allowed
            }

            private void checkForChanges() {
                if (modCount != expectedModCount) {
                    throw new ConcurrentModificationException();
                }
            }
        };
    }

    public static void main(String[] args) {
        FailFastBag<String> bag = new FailFastBag<>();
        for (String s : new String[] {"a", "bb", "c", "dd", "e"}) {
            bag.add(s);
        }

        Iterator<String> it = bag.iterator();
        while (it.hasNext()) {
            if (it.next().length() == 2) {
                it.remove();                       // allowed: goes through the iterator
            }
        }
        StringBuilder left = new StringBuilder();
        bag.forEach(left::append);
        System.out.println("after iterator.remove(): " + left);

        try {
            for (String s : bag) {
                if (s.equals("a")) {
                    bag.add("z");                  // not allowed during iteration
                }
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("add during for-each: ConcurrentModificationException");
        }
    }
}

Output:

Output
after iterator.remove(): ace
add during for-each: ConcurrentModificationException
  • it.remove() removed "bb" and "dd", leaving "ace". The iterator moves its cursor back after shifting the array, so it does not skip the element that slid into the removed slot, and it updates its expected count so its own changes are allowed.
  • bag.add during a for-each changed modCount without the iterator knowing, and the next next() threw ConcurrentModificationException. Without the check, the loop would read a half-updated array and its behaviour would depend on where the change happened.
  • remove() without a preceding next() throws IllegalStateException, matching the JDK. The name "concurrent" is misleading: this check is about modification during iteration in the same thread. It is not thread-safe and does not detect races reliably.

The JDK's own iterator traps

Fail-fast checking is "best effort", and the JDK documents it that way. The program shows a case where it fails silently, the supported ways to remove elements, and two other kinds of iterator.

Java
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class JdkIteratorTraps {

    public static void main(String[] args) {
        // 1. Removing inside for-each usually throws...
        List<String> list = new ArrayList<>(List.of("a", "b", "c", "d"));
        try {
            for (String s : list) {
                if (s.equals("b")) {
                    list.remove(s);
                }
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("1. remove \"b\" in for-each: ConcurrentModificationException");
        }

        // 2. ...but removing the second-to-last element does not, and skips the last one
        List<String> quiet = new ArrayList<>(List.of("a", "b", "c", "d"));
        List<String> visited = new ArrayList<>();
        for (String s : quiet) {
            visited.add(s);
            if (s.equals("c")) {
                quiet.remove(s);                    // size becomes 3 == cursor: loop just ends
            }
        }
        System.out.println("2. remove \"c\": no exception, visited " + visited + ", list " + quiet);

        // 3. The supported ways to remove while iterating
        List<String> viaIterator = new ArrayList<>(List.of("a", "b", "c", "d"));
        for (Iterator<String> it = viaIterator.iterator(); it.hasNext(); ) {
            if (it.next().compareTo("b") <= 0) {
                it.remove();
            }
        }
        List<String> viaRemoveIf = new ArrayList<>(List.of("a", "b", "c", "d"));
        viaRemoveIf.removeIf(s -> s.compareTo("b") <= 0);
        System.out.println("3. iterator.remove: " + viaIterator + ", removeIf: " + viaRemoveIf);

        // 4. An immutable list's iterator does not support remove
        Iterator<String> fixed = List.of("x").iterator();
        fixed.next();
        try {
            fixed.remove();
        } catch (UnsupportedOperationException e) {
            System.out.println("4. List.of iterator remove(): UnsupportedOperationException");
        }

        // 5. A snapshot iterator never throws, and never sees later changes
        List<String> cow = new CopyOnWriteArrayList<>(List.of("a", "b"));
        List<String> seen = new ArrayList<>();
        for (String s : cow) {
            seen.add(s);
            cow.add(s + "!");
        }
        System.out.println("5. CopyOnWriteArrayList saw " + seen + ", now holds " + cow);
    }
}

Output:

Output
1. remove "b" in for-each: ConcurrentModificationException
2. remove "c": no exception, visited [a, b, c], list [a, b, d]
3. iterator.remove: [c, d], removeIf: [c, d]
4. List.of iterator remove(): UnsupportedOperationException
5. CopyOnWriteArrayList saw [a, b], now holds [a, b, a!, b!]
  1. Removing "b" from an ArrayList inside for-each threw ConcurrentModificationException, as expected.
  2. Removing "c", the second-to-last element, threw nothing. After the removal the list had 3 elements and the iterator's cursor was 3, so hasNext() returned false and the loop ended before next() could check modCount. The element "d" was silently never visited. Code that passes tests with one data set can skip elements with another.
  3. Iterator.remove() and Collection.removeIf (Java 8) are the supported ways; both removed "a" and "b". removeIf is shorter, and for ArrayList it is also faster, because it shifts the remaining elements once instead of once per removal.
  4. The iterator of an immutable List.of list throws UnsupportedOperationException from remove().
  5. A CopyOnWriteArrayList iterator walks a snapshot taken when it was created. Adding during the loop never throws, the loop saw only the original two elements, and the list ended with four. That suits listener lists, which are read often and changed rarely.

More ways to remove safely are on the removing elements while iterating page.

A lazy iterator over a tree

An iterator does not need to compute everything up front. This binary search tree's iterator walks it in order using an explicit stack of the nodes still to visit, so its memory use is the height of the tree, and it does only as much work as the caller asks for. The values form a tree of 8 nodes and 4 levels.

Java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;

// A binary search tree whose iterator walks it in order, one node at a time
public class TreeIterator implements Iterable<Integer> {

    private record Node(int value, Node left, Node right) {
        Node insert(int v) {
            if (v < value) {
                return new Node(value, left == null ? new Node(v, null, null) : left.insert(v),
                        right);
            }
            return new Node(value, left,
                    right == null ? new Node(v, null, null) : right.insert(v));
        }
    }

    private Node root;
    private int visitedNodes;                       // counts work, to show laziness

    void add(int v) {
        root = root == null ? new Node(v, null, null) : root.insert(v);
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<>() {
            // The stack holds the path of nodes still to visit; at most the tree height
            private final Deque<Node> stack = new ArrayDeque<>();

            {
                pushLeft(root);
            }

            private void pushLeft(Node n) {
                while (n != null) {
                    stack.push(n);
                    visitedNodes++;
                    n = n.left();
                }
            }

            @Override
            public boolean hasNext() {
                return !stack.isEmpty();
            }

            @Override
            public Integer next() {
                if (stack.isEmpty()) {
                    throw new NoSuchElementException();
                }
                Node n = stack.pop();
                pushLeft(n.right());
                return n.value();
            }
        };
    }

    public static void main(String[] args) {
        TreeIterator tree = new TreeIterator();
        for (int v : new int[] {50, 30, 70, 20, 40, 60, 80, 10}) {
            tree.add(v);
        }
        StringBuilder all = new StringBuilder();
        for (int v : tree) {
            all.append(v).append(' ');
        }
        System.out.println("in order: " + all.toString().trim());

        tree.visitedNodes = 0;
        Iterator<Integer> it = tree.iterator();
        int smallest = it.next();
        int second = it.next();
        System.out.println("two smallest: " + smallest + ", " + second
                + " after touching " + tree.visitedNodes + " of 8 nodes");
    }
}

Output:

Output
in order: 10 20 30 40 50 60 70 80
two smallest: 10, 20 after touching 4 of 8 nodes
  • The full loop printed the values in sorted order, 10 to 80, which is what an in-order walk of a search tree gives.
  • Asking for just the two smallest values touched only 4 of the 8 nodes: the path down the left edge (50, 30, 20, 10). A method that first copied all values into a list would have visited every node, however few the caller needed.
  • A recursive walk would be simpler to write but cannot pause between elements; the explicit stack is what turns recursion into an iterator. TreeMap's iterators instead follow parent links, which needs no stack at all.

Infinite iterators, streams, and the one-shot trap

An iterator whose hasNext() always returns true is a lazy infinite sequence. The program generates Fibonacci numbers, turns the iterator into a Stream, and then shows what goes wrong when an Iterable does not create a new iterator each time.

Java
import java.util.Iterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class LazyAndSpliterator {

    // An infinite, lazy iterator: Fibonacci numbers computed only when asked for
    static Iterator<Long> fibonacci() {
        return new Iterator<>() {
            private long a = 0;
            private long b = 1;

            @Override
            public boolean hasNext() {
                return true;                       // never ends
            }

            @Override
            public Long next() {
                long result = a;
                long sum = a + b;
                a = b;
                b = sum;
                return result;
            }
        };
    }

    public static void main(String[] args) {
        Iterator<Long> fib = fibonacci();
        StringBuilder first = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            first.append(fib.next()).append(' ');
        }
        System.out.println("first 10: " + first.toString().trim());

        // Wrap any iterator as a Stream through a Spliterator
        Spliterator<Long> split =
                Spliterators.spliteratorUnknownSize(fibonacci(), Spliterator.ORDERED);
        Stream<Long> stream = StreamSupport.stream(split, false);
        long found = stream.filter(n -> n % 2 == 0 && n > 1000).findFirst().orElseThrow();
        System.out.println("first even Fibonacci over 1000: " + found);

        // Trap: an Iterable that hands out the same iterator works only once
        Iterator<Long> shared = fibonacciUpTo(20);
        Iterable<Long> oneShot = () -> shared;
        Iterable<Long> reusable = () -> fibonacciUpTo(20);
        System.out.println("one-shot, 1st loop: " + count(oneShot) + " values, 2nd loop: "
                + count(oneShot));
        System.out.println("reusable, 1st loop: " + count(reusable) + " values, 2nd loop: "
                + count(reusable));
    }

    static Iterator<Long> fibonacciUpTo(long max) {
        Iterator<Long> all = fibonacci();
        return new Iterator<>() {
            private Long next = all.next();

            @Override
            public boolean hasNext() {
                return next <= max;
            }

            @Override
            public Long next() {
                Long v = next;
                next = all.next();
                return v;
            }
        };
    }

    static int count(Iterable<Long> values) {
        int n = 0;
        for (long ignored : values) {
            n++;
        }
        return n;
    }
}

Output:

Output
first 10: 0 1 1 2 3 5 8 13 21 34
first even Fibonacci over 1000: 2584
one-shot, 1st loop: 8 values, 2nd loop: 0
reusable, 1st loop: 8 values, 2nd loop: 8
  • Only the requested values were ever computed: ten for the first line, and for the stream exactly as many as findFirst needed to reach 2,584, the first even Fibonacci number above 1,000.
  • Spliterators.spliteratorUnknownSize wraps any iterator, and StreamSupport.stream(split, false) makes a sequential stream from it. Pass true only if the work per element is large, because a spliterator built from an iterator splits poorly for parallel streams.
  • The lambda () -> shared is a valid Iterable, but it returns the same iterator every time. The first loop consumed the 8 values up to 20; the second loop found the iterator exhausted and saw 0. The reusable version creates a new iterator per call and gave 8 both times. This bug often appears when an Iterator from an API is wrapped to use it in a for-each.

Index loops versus iterators

For an ArrayList, get(i) is an array access, but for a LinkedList it walks the list from the nearer end every time. Summing 50,000 elements both ways on both lists shows what that means. Times are the best of 3 runs, in microseconds; a rough comparison.

Java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class LoopSpeed {

    interface Sum {
        long run(List<Integer> list);
    }

    static long time(List<Integer> list, Sum sum) {
        long best = Long.MAX_VALUE;
        for (int r = 0; r < 3; r++) {
            long t0 = System.nanoTime();
            sum.run(list);
            best = Math.min(best, System.nanoTime() - t0);
        }
        return best / 1000;                        // microseconds
    }

    public static void main(String[] args) {
        int n = 50000;
        List<Integer> array = new ArrayList<>();
        List<Integer> linked = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            array.add(i);
            linked.add(i);
        }
        Sum byIndex = l -> {
            long s = 0;
            for (int i = 0; i < l.size(); i++) {
                s += l.get(i);
            }
            return s;
        };
        Sum byIterator = l -> {
            long s = 0;
            for (Iterator<Integer> it = l.iterator(); it.hasNext(); ) {
                s += it.next();
            }
            return s;
        };
        System.out.printf("%,d elements, best of 3:%n", n);
        System.out.printf("ArrayList  get(i): %,9d us   iterator: %,6d us%n",
                time(array, byIndex), time(array, byIterator));
        System.out.printf("LinkedList get(i): %,9d us   iterator: %,6d us%n",
                time(linked, byIndex), time(linked, byIterator));
    }
}

Output (2-CPU Linux machine, JDK 21):

Output
50,000 elements, best of 3:
ArrayList  get(i):       326 us   iterator:    350 us
LinkedList get(i):   879,728 us   iterator:    724 us
  • On the ArrayList, both loops took well under a millisecond, and which one is faster varies between runs.
  • On the LinkedList, the index loop took the better part of a second while the iterator still took under a millisecond, more than a thousand times faster. Each get(i) walks up to 25,000 nodes, so the loop does about 625 million node steps in total; the iterator just follows one link per element.
  • Code written against List should therefore iterate with for-each or an iterator, unless it knows the list implements RandomAccess, the marker interface that ArrayList has and LinkedList lacks. See ArrayList versus LinkedList.

Choosing how to iterate

Iteration recipes
SituationUse
Make a class usable in for-eachImplement Iterable and return a new Iterator from each iterator() call
Remove while loopingremoveIf, or Iterator.remove()
Change elements while looping over a listListIterator.set, or replaceAll
A lazy or infinite sequenceA custom Iterator, or Stream.iterate / Stream.generate
Turn an iterator into a streamStreamSupport.stream(Spliterators.spliteratorUnknownSize(it, ORDERED), false)
Iterate while other code may add elementsA snapshot: CopyOnWriteArrayList, or copy the collection first
Loop over a List of unknown typefor-each, not get(i)
Hot loop over numbersAn array, IntStream, or PrimitiveIterator.OfInt

See Iterator versus ListIterator and advanced streams for spliterators in more depth.