The Iterable Interface: Purpose and Contract
You'll learn what Iterable<T> is and how it enables the enhanced for-loop syntax.
What Is Iterable?
Iterable<T> is a fundamental interface in Java that marks a class as capable of being iterated over. It's the contract that says: "I can provide an Iterator to traverse my elements." Any class implementing Iterable<T> can be used in Java's enhanced for-loop (the "for-each" loop).
Think of Iterable as a vending machine interface: the machine doesn't give you all the snacks at once—it provides a mechanism (the Iterator) to retrieve items one at a time.
The Single Method Contract
The Iterable<T> interface declares just one method:
Iterator<T> iterator()
This method must return an Iterator<T> that allows traversal through the collection's elements. When you write an enhanced for-loop, Java automatically calls this iterator() method behind the scenes.
Why It Matters
Every major collection class you've learned—ArrayList, LinkedList, HashSet, TreeMap.keySet(), and others—implements Iterable. That's why you can use the enhanced for-loop with them:
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
// This works because List extends Iterable
for (String name : names) {
System.out.println(name);
}
Under the hood, the compiler translates this to an explicit Iterator loop using the iterator() method you've already learned.
Key Takeaway: Iterable<T> is the simple contract (one method: iterator()) that enables enhanced for-loops and marks objects as traversable—it's the foundation that all Java collections build upon.