interface Iterator<T> {
    boolean hasNext();
    T next();
}

interface IterableCollection<T> {
    Iterator<T> createIterator();
}

class BrowseHistory implements IterableCollection<String> {
    private String[] urls = new String[10];
    private int count = 0;

    void push(String url) {
        urls[count++] = url;
    }

    String pop() {
        return urls[--count];
    }

    public Iterator<String> createIterator() {
        return new HistoryIterator(this);
    }

    private class HistoryIterator implements Iterator<String> {
        private BrowseHistory history;
        private int index = 0;

        HistoryIterator(BrowseHistory history) {
            this.history = history;
        }

        public boolean hasNext() {
            return index < history.count;
        }

        public String next() {
            return history.urls[index++];
        }
    }
}

public static void main(String[] args) {
    BrowseHistory history = new BrowseHistory();
    history.push("a.com");
    history.push("b.com");
    history.push("c.com");

    Iterator<String> iterator = history.createIterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
}
Back to Design Patterns
Behavioral Design Pattern

Iterator

The Iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It decouples the traversal logic from the collection itself, allowing multiple concurrent traversals and uniform iteration across different data structures.