Iterator Design Pattern

Back To Index

Overview

The Iterator Design Pattern provides a way to access the elements of a collection sequentially without exposing its underlying representation. It is commonly used to traverse collections such as lists, sets, or maps.

Key Characteristics

Implementation

The following is an example of an Iterator implementation in Java:


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

// Collection
class BookCollection implements Iterable {
    private List books = new ArrayList<>();

    public void addBook(String book) {
        books.add(book);
    }

    public void removeBook(String book) {
        books.remove(book);
    }

    @Override
    public Iterator iterator() {
        return books.iterator();
    }
}

// Demo
public class IteratorDemo {
    public static void main(String[] args) {
        BookCollection collection = new BookCollection();
        collection.addBook("Book 1");
        collection.addBook("Book 2");
        collection.addBook("Book 3");

        Iterator iterator = collection.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // Enhanced for loop (for-each) with Iterable
        for (String book : collection) {
            System.out.println("[Enhanced] " + book);
        }
    }
}
    

When to Use

Advantages

Disadvantages

Back To Index