The Iterable and Iterator Contracts
Understand the Iterable and Iterator interfaces and how for-each loops work internally.
Iterable and Iterator
Iterable<T> and Iterator<T> are the interfaces that power Java's for-each loop. Understanding them lets you make your own data structures loop-compatible.
The Iterable Interface
Iterable<T> has one method: iterator() that returns an Iterator<T>. Any class implementing Iterable can be used in a for-each loop.
// java.lang.Iterable<T>
interface Iterable<T> {
Iterator<T> iterator();
// default: forEach, spliterator (Java 8+)
}
// Any class implementing Iterable<T> works in for-each:
class Range implements Iterable<Integer> {
private final int start, end;
Range(int start, int end) { this.start = start; this.end = end; }
public Iterator<Integer> iterator() {
return new RangeIterator(); // defined separately
}
}All lessons in this course
- The Iterable and Iterator Contracts
- Implementing a Custom Iterator
- ListIterator and Bidirectional Traversal
- Fail-Fast vs Fail-Safe Iterators