Java › Inner Classes & Anonymous Classes

How would you implement the classic Iterator design pattern using a private non-static inner class, letting the inner Iterator implementation access the outer collection's private internal state directly?

Advanced

Answer

A custom collection class implementing Iterable<T> commonly defines its iterator() method to return an instance of a private, non-static inner class implementing Iterator<T> -- since the inner class automatically has an implicit reference to its specific enclosing collection instance, it can directly access the outer collection's private internal fields (like the backing array or linked node structure) needed to implement hasNext()/next() correctly, without requiring any public accessor methods on the outer class that would otherwise need to exist purely to expose this internal state to an external, unrelated Iterator implementation.
public class LinkedStack<T> implements Iterable<T> {
    private Node<T> head;
    private static class Node<T> { T value; Node<T> next; }

    public Iterator<T> iterator() {
        return new StackIterator();  // private inner class instance
    }

    private class StackIterator implements Iterator<T> {
        private Node<T> current = head;  // directly accesses the OUTER instance's private 'head' field
        public boolean hasNext() { return current != null; }
        public T next() {
            T value = current.value;
            current = current.next;
            return value;
        }
    }
}
Real-world example A custom LinkedStack collection's private inner StackIterator class directly reads the outer instance's private head field to traverse the underlying linked structure, keeping this traversal logic entirely private and encapsulated within the collection class itself rather than requiring any public getter methods that would otherwise leak the internal node structure to external code.

Common follow-ups: Why is the Node class itself made a static nested class while the Iterator is a non-static inner class -- what's the reasoning behind that specific choice for each?;How would you support creating multiple independent iterators over the same collection simultaneously, and does this inner-class design naturally support that?