100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

What is the Iterator Pattern?

Learn the Iterator design pattern — hasNext/next, decoupling traversal from storage — with a Java example and interview questions.

easyQ39 of 226 in Object Oriented Programming Est. time: 4 minsLast updated:
Open Code Lab

Expected Interview Answer

The Iterator pattern provides a standard way to access the elements of a collection sequentially without exposing its underlying representation, using a separate iterator object that tracks traversal position.

An Iterator interface typically declares hasNext() and next(), and each collection type provides its own concrete iterator that knows how to walk its particular internal structure — an array, a linked list, or a tree. The client code only interacts with the Iterator interface, so the same traversal loop works regardless of whether the underlying collection is an ArrayList or a LinkedList. This decouples traversal logic from the collection’s storage details, and it allows multiple independent iterators to traverse the same collection concurrently, each maintaining its own position. Most modern languages, including Java’s Iterable/Iterator interfaces and the for-each loop, bake this pattern directly into the language.

  • Exposes a uniform traversal interface regardless of internal storage
  • Hides the collection’s internal structure from client code
  • Supports multiple simultaneous, independent traversals
  • Lets new collection types plug into existing traversal code unchanged

AI Mentor Explanation

A scorer flipping through a stack of ball-by-ball cards doesn’t need to know whether the cards are stored in a spiral binder or a loose folder — they just ask 'is there a next card?' and 'give me the next card' each time. That request-response protocol is the iterator: a small object that tracks position and exposes a uniform way to move through the deliveries, regardless of how the cards are physically organized underneath. Two scorers can flip through independent copies of the card stack at their own pace without interfering with each other.

Step-by-Step Explanation

  1. Step 1

    Define the Iterator interface

    Declare hasNext() and next() as the uniform traversal contract.

  2. Step 2

    Implement a concrete iterator per collection

    Each collection type provides an iterator that knows its own internal storage.

  3. Step 3

    Expose iterator creation on the collection

    The collection implements an Iterable-style method that returns a fresh iterator.

  4. Step 4

    Traverse via the interface only

    Client code loops using hasNext()/next(), never touching the collection’s internals directly.

What Interviewer Expects

  • A clear definition: uniform sequential access without exposing internal structure
  • Mention of hasNext()/next() as the standard contract
  • Understanding that different collections can share the same client traversal code
  • Awareness that multiple independent iterators can traverse the same collection

Common Mistakes

  • Confusing Iterator with simply looping over an array with an index
  • Modifying a collection while iterating without handling ConcurrentModificationException
  • Believing an iterator can be reused after it is exhausted without resetting
  • Thinking Iterator and Iterable are the same interface in Java (Iterable produces an Iterator)

Best Answer (HR Friendly)

The Iterator pattern gives you a standard way to go through the elements of a collection one at a time — 'is there a next item?' and 'give me the next item' — without needing to know or care how that collection actually stores its data underneath. It’s what makes a for-each loop work the same way whether you’re iterating a list, a set, or a tree.

Code Example

Custom Iterator over a simple collection
import java.util.Iterator;
import java.util.NoSuchElementException;

class NameCollection implements Iterable<String> {
    private final String[] names;
    NameCollection(String[] names) { this.names = names; }

    public Iterator<String> iterator() {
        return new Iterator<String>() {
            private int index = 0;
            public boolean hasNext() { return index < names.length; }
            public String next() {
                if (!hasNext()) throw new NoSuchElementException();
                return names[index++];
            }
        };
    }
}

NameCollection collection = new NameCollection(new String[]{"Ana", "Ben", "Cid"});
for (String name : collection) {
    System.out.println(name); // Ana, Ben, Cid
}

Follow-up Questions

  • What is the difference between Iterable and Iterator in Java?
  • What happens if you modify a collection while iterating over it?
  • Can two iterators traverse the same collection independently at the same time?
  • How does a for-each loop relate to the Iterator pattern under the hood?

MCQ Practice

1. What is the primary goal of the Iterator pattern?

Iterator standardizes traversal across different collection types while hiding their internal storage details.

2. Which two methods form the core Iterator contract?

hasNext() checks for remaining elements, and next() returns the next element while advancing position.

3. What does it mean that iterators are independent?

Each iterator instance maintains its own cursor, so several traversals of the same collection can proceed independently.

Flash Cards

Iterator pattern in one line?A uniform way to traverse a collection’s elements sequentially without exposing its internal structure.

Core contract?hasNext() to check for more elements, next() to retrieve the next one.

Key benefit?Client traversal code works the same regardless of the collection’s underlying storage.

Iterable vs Iterator in Java?Iterable exposes iterator(), which returns an Iterator that actually performs the traversal.

1 / 4

Continue Learning