Iterable vs Iterator

What is Iterable?

The Iterable interface represents a collection of elements that can be iterated over. Classes that implement Iterable promise that they can produce an Iterator. It contains a single abstract method: iterator(), which returns an Iterator for the collection. This interface is what allows you to use the enhanced for-each loop syntax:

for(Type element:iterableObject)

Iterable interface:

public interface Iterable<T> {
    Iterator<T> iterator();
}

What is Iterator?

Iterator is an object that performs the actual iteration.

public interface Iterator<T> {
    boolean hasNext();

    T next();

    default void remove();
}

Key points:

  • Retrieves elements one at a time
  • Controls the iteration
  • Methods: hasNext(), next(), remove()
  • Created by calling collection.iterator()

Example:

Iterator<String> it = names.iterator();

while(it.

hasNext()){
        System.out.

println(it.next());
        }

Iterator

The Iterator interface provides the mechanism for traversing the elements of a collection, one by one. It defines methods for checking if there are more elements hasNext(), retrieving the next element next(), and optionally removing the current element remove(). An Iterator maintains the state of the iteration, meaning it keeps track of the current position within the collection. Each call to the iterator() method of an Iterable object typically returns a new Iterator instance, allowing for multiple independent traversals of the same collection.

Iterable vs Iterator (Side-by-Side)

Feature Iterable Iterator
Purpose Represents a collection Represents a cursor for iteration
Main Role Provides iterator() Provides next(), hasNext(), remove()
Used In For-each loop Manual loops
Return Type Iterator A single element
Collections Support Yes Not necessarily

Analogy

Think of:

  • Iterable → a book
  • Iterator → a bookmark moving page by page

Iterable gives you the “tool” (iterator) to read the book,
Iterator moves through the book one step at a time.


below is the example of how to implement the iterable and iterator interface.

package org.example.genericlist;

import java.util.Iterator;

/***
 * GenericList kind of ArrayList
 */
public class GenericList<T> implements Iterable<T> {
    private final T[] items = (T[]) new Object[10];
    private int count;

    public void add(T item) {
        items[count++] = item;
    }

    public T get(int index) {
        return items[index];
    }

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

    public void removeAt(int index) {
        if (index < 0 || index >= count)
            throw new IndexOutOfBoundsException();

        for (int i = index; i < count - 1; i++) {
            items[i] = items[i + 1];
        }
        items[count - 1] = null;
        count--;
    }

    private static class ListIterator<T> implements Iterator<T> {
        GenericList<T> list;
        private int index;
        private int lastReturned = -1;

        public ListIterator(GenericList<T> list) {
            this.list = list;
        }

        @Override
        public boolean hasNext() {
            return list.count > index;
        }

        @Override
        public T next() {
            lastReturned = index;
            return list.items[index++];
        }

        @Override
        public void remove() {
            if (lastReturned < 0)
                throw new IllegalStateException("next() not called or remove() already called");

            list.removeAt(lastReturned);
            index--;            // shift cursor back because list shrank
            lastReturned = -1;  // reset
        }
    }
}