Iterable and Iterator Interfaces

Iterable Interface

  • The Iterable interface represents a collection of elements which can be iterated (looped) over.
  • It is a root interface in the Java Collections Framework defined in java.lang package.
  • Any class implementing Iterable can be the target of the enhanced for-each loop.
  • It contains a single method: iterator() which returns an Iterator.

Iterator Interface

  • The Iterator interface provides methods to iterate over elements in a collection.
  • It allows traversal, element access, and element removal during iteration.
  • It is typically obtained from an Iterable.
  • It is defined in java.util package.

Example : Using Iterable and Iterator with an ArrayList

import java.util.ArrayList;
import java.util.Iterator;

public class IterableIteratorExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C++");

        // Using Iterable's iterator() method
        Iterator<String> iterator = list.iterator();

        // Iterating using Iterator methods
        while (iterator.hasNext()) {
            String language = iterator.next();
            System.out.println(language);
        }
    }
}
/*
Java
Python
C++
*/

The Iterable and Iterator interfaces form the backbone of Java’s iteration mechanism, enabling seamless traversal over collections of elements. The Iterable interface provides a standardized way for a collection to expose an iterator, allowing it to be used in enhanced for-loops and other iteration contexts. Meanwhile, the Iterator interface offers methods to safely traverse elements one-by-one, with support for checking the presence of next elements (hasNext()), retrieving elements (next()), and optionally removing elements (remove()).

Together, these interfaces promote clean, consistent, and flexible iteration over various data structures, whether built-in collections like ArrayList or custom collections created by developers. Understanding and implementing these interfaces is fundamental to effective Java programming and empowers developers to write reusable, modular, and easy-to-maintain code.


Scroll to Top