Implementing Iterable in Custom Classes
What you'll learn: How to make your own custom class work with the enhanced for loop by implementing the Iterable interface.
The Core Idea
When you implement the Iterable<E> interface in your custom class, you're giving Java the blueprint it needs to iterate over your objects using the enhanced for loop (for-each). The only requirement? Implement the iterator() method to return a custom Iterator that knows how to traverse your data.
Think of it like providing directions to a tour guide. Your class holds the attractions (data), but the iterator is the guide who knows the route through them.
How It Works
Your custom class must:
- Declare that it implements
Iterable<E>(whereEis your element type) - Implement the
iterator()method - Return an
Iterator<E>instance (often a custom inner class)
The Iterator you return handles the actual traversal logic with hasNext(), next(), and optionally remove().
A Simple Example
public class NumberRange implements Iterable<Integer> {
private int start;
private int end;
public NumberRange(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public Iterator<Integer> iterator() {
return new RangeIterator();
}
private class RangeIterator implements Iterator<Integer> {
private int current = start;
@Override
public boolean hasNext() {
return current <= end;
}
@Override
public Integer next() {
return current++;
}
}
}
// Now you can use it:
NumberRange range = new NumberRange(1, 5);
for (Integer num : range) {
System.out.println(num); // Prints 1, 2, 3, 4, 5
}
Key Takeaway: Implementing Iterable in your custom class requires defining an iterator() method that returns a working Iterator instance, enabling your objects to work seamlessly with Java's enhanced for loop.