Enhanced for Loops and the Iterable Interface
You'll learn: How enhanced for loops work with any collection type that implements the Iterable interface, not just arrays.
Beyond Arrays: The Power of Iterable
You've already seen enhanced for loops work beautifully with arrays. But here's the secret: the enhanced for loop was actually designed to work with any object that implements the Iterable interface. Arrays are just one special case that Java handles for you automatically.
What Is Iterable?
Think of Iterable as a contract: "I promise I can hand you my elements one at a time." Any class that implements this interface is saying, "You can use an enhanced for loop on me!"
Many of Java's built-in collection types implement Iterable, which means you can loop through them with the same clean syntax:
// Works with any Iterable collection
for (String name : someCollection) {
System.out.println(name);
}
How the Enhanced for Loop Actually Works
Behind the scenes, when you write an enhanced for loop on an Iterable object, Java automatically calls methods to get each element in sequence. The loop handles all the details of fetching elements—you just focus on what to do with each one.
This is why the enhanced for loop is sometimes called the "for-each" loop: it's designed to say "for each element in this collection."
The Unified Pattern
Whether you're iterating through an array or any Iterable collection, the syntax stays identical. This consistency makes your code cleaner and more readable across different data structures.
Key Takeaway: Enhanced for loops work with arrays AND any object implementing Iterable, giving you a uniform, readable way to process elements sequentially without worrying about indices or iteration mechanics.