Sobes.tech
Junior

What is the Iterable interface in Java?

sobes.tech AI

Answer from AI

Iterable<T> is an interface in Java that allows objects to become "iterable," meaning they can be traversed using a for-each loop. It indicates that a class implementing this interface can return an Iterator.

Key points:

  • Contains a single abstract method iterator(), which returns an object of type Iterator<T>.
  • Supports the enhanced for loop (for-each).
  • Is a parent interface of Collection. All implementations of Collection (such as ArrayList, HashSet, LinkedList) implement Iterable and are therefore iterable.

Example usage:

// Example of a class implementing Iterable
import java.util.Iterator;

class MyIterableCollection<T> implements Iterable<T> {
    private T[] items;
    private int size;

    // constructor and add methods...

    @Override
    public Iterator<T> iterator() {
        return new MyIterator();
    }

    // Inner class for the iterator
    private class MyIterator implements Iterator<T> {
        private int currentIndex = 0;

        @Override
        public boolean hasNext() {
            return currentIndex < size;
        }

        @Override
        public T next() {
            return items[currentIndex++];
        }
    }
}

// Usage in a for-each loop
class Main {
    public static void main(String[] args) {
        MyIterableCollection<String> collection = new MyIterableCollection<>();
        // Adding elements...

        for (String item : collection) {
            System.out.println(item); // Can iterate thanks to Iterable
        }
    }
}