For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt, and this page is available as Markdown at https://nhanbe.id.vn/design-patterns/behavioral/iterator.md.

Provide a way to access elements of a collection sequentially without exposing its representation. You want consistent traversal across differen

Iterator

Overview

Provide a way to access elements of a collection sequentially without exposing its representation.

When to use

  • You want consistent traversal across different structures.
  • You need multiple traversal strategies.

Java example

class Range implements Iterable<Integer> {
    private final int start, end;
    Range(int start, int end) { this.start = start; this.end = end; }

    public Iterator<Integer> iterator() {
        return new Iterator<>() {
            private int current = start;
            public boolean hasNext() { return current <= end; }
            public Integer next() { return current++; }
        };
    }
}

TypeScript example

class Range implements Iterable<number> {
  constructor(private start: number, private end: number) {}
  *[Symbol.iterator](): Iterator<number> {
    for (let i = this.start; i <= this.end; i++) yield i;
  }
}

Pros and cons

Pros:

  • Hides internal structure.
  • Enables multiple traversal algorithms.

Cons:

  • Extra objects for simple collections.

Common pitfalls

  • Exposing mutable internals through iterator.
  • Ignoring concurrent modification semantics.