The Iterable Interface and for-each Loops
What you'll learn: How the Iterable interface enables enhanced for-each loops and defines the contract for iteration in Java collections.
The Foundation of Enhanced For Loops
You've been using enhanced for loops (for-each loops) with collections throughout your learning journey, but now let's understand the mechanism behind them. Every collection that implements the Collection interface can be used in a for-each loop because Collection extends Iterable<E>.
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
// This enhanced for loop works because List extends Collection extends Iterable
for (String name : names) {
System.out.println(name);
}
The Iterable Contract
The Iterable interface defines a single method:
Iterator<E> iterator()
Any class implementing Iterable must provide this method, which returns an Iterator object. Behind the scenes, when you write a for-each loop, the compiler transforms it into code that calls iterator() and uses the returned Iterator to traverse the elements.
Think of Iterable as a guarantee: "I promise I can give you a way to step through my elements one at a time."
Why This Matters
Because Collection extends Iterable, all collection types—ArrayList, HashSet, LinkedList, and others—automatically work with for-each loops. You don't need to learn different syntax for different collections.
Set<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
for (Integer num : numbers) { // Works identically to lists
System.out.println(num);
}
Key Takeaway: The Iterable interface is the foundation for enhanced for-each loops in Java. By extending Iterable, the Collection interface ensures all collection types can be iterated uniformly using the same clean, readable syntax.