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 forjava.lang.IterableIterable
- Call
once to get a freshiterable.iterator() .Iterator - Loop while
returns true, callinghasNext() to get each element.next()
So for (T x : items)for (Iterator<T> it = items.iterator(); it.hasNext(); ) { T x = it.next(); ... }Iterator
must have no visible side effects: calling it twice in a row must give the same answer and must not skip an element.hasNext() must thrownext() when there are no more elements, not return null.NoSuchElementException is optional. Since Java 8 its default implementation throwsremove() ; when supported, it removes the element last returned byUnsupportedOperationException and may be called once pernext() .next() should return a new, independent iterator on every call, so the same object can be looped over again and by two loops at once.iterator()
| Interface | Since | Adds | Best for |
|---|---|---|---|
Enumeration | Java 1.0 | hasMoreElementsnextElement | Old APIs only (VectorHashtableasIterator() |
Iterator | Java 1.2 | hasNextnextremoveforEachRemaining | Walking any sequence one element at a time |
ListIterator | Java 1.2 | Backwards movement, setadd | Editing a list in place while walking it |
Iterable | Java 5 | iterator()forEachspliterator | Anything usable in for-each |
Spliterator | Java 8 | Splitting for parallelism, characteristics, size estimates | Feeding streams |
PrimitiveIterator.OfInt | Java 8 | nextInt() | Iterating 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
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:
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
creates a new anonymous iterator with its owniterator() field each time. The range object itself holds no iteration state.next - Calling
after the last element threwnext() , as the contract requires.NoSuchElementException callsnext() itself, so a caller that skips the check still gets the right exception.hasNext() came for free: it is a default method offorEach (Java 8) that runs the same loop with a lambda.Iterable- The range yields
objects, so every element is boxed. For a hot numeric loop, implementInteger , or just usePrimitiveIterator.OfInt .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 modCountremove()
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:
after iterator.remove(): ace
add during for-each: ConcurrentModificationException
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.it.remove() during a for-each changedbag.add without the iterator knowing, and the nextmodCount threwnext() . Without the check, the loop would read a half-updated array and its behaviour would depend on where the change happened.ConcurrentModificationException without a precedingremove() throwsnext() , 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.IllegalStateException
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.
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:
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!]
- Removing "b" from an
inside for-each threwArrayList , as expected.ConcurrentModificationException - 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
returned false and the loop ended beforehasNext() could checknext() . The element "d" was silently never visited. Code that passes tests with one data set can skip elements with another.modCount andIterator.remove() (Java 8) are the supported ways; both removed "a" and "b".Collection.removeIf is shorter, and forremoveIf it is also faster, because it shifts the remaining elements once instead of once per removal.ArrayList- The iterator of an immutable
list throwsList.of fromUnsupportedOperationException .remove() - A
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.CopyOnWriteArrayList
More ways to remove safely are on the
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.
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:
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.
's iterators instead follow parent links, which needs no stack at all.TreeMap
Infinite iterators, streams, and the one-shot trap
An iterator whose hasNext()StreamIterable
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:
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
needed to reach 2,584, the first even Fibonacci number above 1,000.findFirst wraps any iterator, andSpliterators.spliteratorUnknownSize makes a sequential stream from it. PassStreamSupport.stream(split, false) only if the work per element is large, because a spliterator built from an iterator splits poorly for parallel streams.true- The lambda
is a valid() -> shared , 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 anIterable from an API is wrapped to use it in a for-each.Iterator
Index loops versus iterators
For an ArrayListget(i)LinkedList
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):
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
, both loops took well under a millisecond, and which one is faster varies between runs.ArrayList - On the
, the index loop took the better part of a second while the iterator still took under a millisecond, more than a thousand times faster. EachLinkedList 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.get(i) - Code written against
should therefore iterate with for-each or an iterator, unless it knows the list implementsList , the marker interface thatRandomAccess has andArrayList lacks. SeeLinkedListArrayList versus LinkedList .
Choosing how to iterate
| Situation | Use |
|---|---|
| Make a class usable in for-each | Implement IterableIteratoriterator() |
| Remove while looping | removeIfIterator.remove() |
| Change elements while looping over a list | ListIterator.setreplaceAll |
| A lazy or infinite sequence | A custom IteratorStream.iterateStream.generate |
| Turn an iterator into a stream | StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, ORDERED), false) |
| Iterate while other code may add elements | A snapshot: CopyOnWriteArrayList |
Loop over a List | for-each, not get(i) |
| Hot loop over numbers | An array, IntStreamPrimitiveIterator.OfInt |
See