What is the Iterator pattern?

Answer

The Iterator pattern provides a standard way to sequentially access elements of a collection without exposing the underlying representation. It decouples traversal logic from the collection itself. Key interfaces (Java): interface Iterator<E> { boolean hasNext(); // Does another element exist? E next(); // Get next element, advance pointer } interface Iterable<E> { Iterator<E> iterator(); // Return an iterator }. Custom collection with iterator: class NumberRange implements Iterable<Integer> { private int start; private int end; public NumberRange(int start, int end) { this.start = start; this.end = end; } @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { int current = start; @Override public boolean hasNext() { return current <= end; } @Override public Integer next() { if (!hasNext()) throw new NoSuchElementException(); return current++; } }; } } // Usage with for-each (uses Iterable): for (int n : new NumberRange(1, 5)) { System.out.println(n); // 1 2 3 4 5 } // Explicit iterator: Iterator<Integer> it = range.iterator(); while (it.hasNext()) { System.out.println(it.next()); }. Real-world uses: all Java collections (List, Set, Map.entrySet()) are Iterable. Allows for-each loops on custom classes. Java streams build on iterators. External vs Internal iterator: external (client controls) vs internal (collection controls, lambda): list.forEach(item -> process(item)); // Internal. Python implements with __iter__ and __next__. C# uses IEnumerable and yield return.