Iterable interface and its usage

The Iterable interface in Java is a fundamental interface in the java.lang package that allows objects to be iterated using the enhanced for loop (for-each loop). It defines a single method iterator() that returns an Iterator object, which in turn allows sequential access to elements contained within the implementing class. Let’s delve into the Iterable interface, its usage, and how it facilitates iteration over collections.

Understanding the Iterable Interface

The Iterable interface serves as the root interface for all collection classes in Java. It enables objects to be the target of the enhanced for loop (for-each loop), providing a standard way to iterate over elements. The interface itself is quite simple:

public interface Iterable<T> {

    Iterator<T> iterator();

}

iterator() Method: This method returns an Iterator object, which allows sequential access to elements in the implementing class.

import java.util.Iterator;

public class StudentList implements Iterable<String> {
    private String[] students;
    private int size;
    
    public StudentList(int capacity) {
        students = new String[capacity];
        size = 0;
    }
    
    public void add(String student) {
        if (size < students.length) {
            students[size++] = student;
        }
    }
    
    @Override
    public Iterator<String> iterator() {
        return new StudentIterator();
    }
    
    private class StudentIterator implements Iterator<String> {
        private int index = 0;

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

        @Override
        public String next() {
            return students[index++];
        }
    }
    
    public static void main(String[] args) {
        StudentList studentList = new StudentList(5);
        studentList.add("Paani");
        studentList.add("Mahesh");
        studentList.add("Datta");
        studentList.add("Ganesh");
        studentList.add("Harsha");

        // Using enhanced for loop to iterate over StudentList
        System.out.println("Student names:");
        for (String student : studentList) {
            System.out.println(student);
        }
    }
}

/*
D:\>javac StudentList.java

D:\>java StudentList
Student names:
Paani
Mahesh
Datta
Ganesh
Harsha
*/

The Iterable interface in Java is a cornerstone for enabling objects to be iterated using the enhanced for loop (for-each loop). By implementing Iterable and providing an Iterator, custom classes can support iteration over their elements, enhancing code readability and simplifying iteration logic. Understanding how to utilize the Iterable interface empowers Java developers to design and implement iterable collections and data structures efficiently.

Scroll to Top