Course contentsShow
← Java
Lesson 1293 of 2,87029. Iterators and IterableFree lesson

Implementing Iterable in Custom Classes

Creating your own iterable class by implementing iterator() to return a custom Iterator.

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:

  1. Declare that it implements Iterable<E> (where E is your element type)
  2. Implement the iterator() method
  3. 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.