SyntaxPilot
Courses/Low-Level Design/Lesson 40
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 40 of 90

Iterator pattern

Iterator patternIterator interfaceIterablehasNext and nextfor-each loopinternal vs external iterationcustom iteratorsfail-fast iteratorsfail-safe iteratorsConcurrentModificationExceptionSpliterator overview

These are the notes for Low-Level Design (LLD) episode 40, the seventh behavioural pattern (patterns about how objects share work and talk to each other). An iterator walks through a collection one item at a time, so the code using it never needs to know how the collection is stored inside. We start with a TV remote, watch a waiter app stop compiling when the chef changes how a menu is stored, and invent the pattern as the fix. Then we look at the for-each loop, the iterator contract, ConcurrentModificationException, fail-fast and fail-safe iterators, internal iteration and the Spliterator. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs are real.

1. The real-life idea: the Next button on a TV remote

With a TV remote In code
Cable, dish or internet TV: each stores channels its own way An aggregate (a collection): an object that holds many items, like a list, a set or a menu
The remote: you never open the TV box An iterator: an object whose only job is to walk a collection, one item at a time
"Any more channels?" hasNext(): true if another item is waiting, false at the end
Press Next next(): hands over the next item and moves forward

The same two buttons work on every kind of TV. That is the whole idea.

2. The problem: the waiter knows too much

Asha's cafe keeps the breakfast menu in an array (String[]) and the lunch menu in an ArrayList. The waiter app prints every menu:

import java.util.*;
class BreakfastMenu { String[] items = {"Poha", "Upma", "Idli"}; }       // an array
class LunchMenu { List<String> items = new ArrayList<>(List.of("Thali", "Biryani")); }
class Waiter {
    void printAll(BreakfastMenu b, LunchMenu l) {
        for (int i = 0; i < b.items.length; i++)                  // knows: it's an array
            System.out.println(b.items[i]);
        for (int i = 0; i < l.items.size(); i++)                  // knows: it's a list
            System.out.println(l.items.get(i));
    }
}
public class Main {
    public static void main(String[] args) {
        new Waiter().printAll(new BreakfastMenu(), new LunchMenu());
    }
}

Output (real):

Poha
Upma
Idli
Thali
Biryani

It works, but printAll uses .length and [i] because it knows breakfast is an array, and size() and get(i) because it knows lunch is a list.

Now the chef changes the breakfast menu to an ArrayList, so dishes are easy to add and remove. Nobody touches the waiter:

import java.util.*;
class BreakfastMenu { List<String> items = new ArrayList<>(List.of("Poha", "Upma")); }
class LunchMenu { List<String> items = new ArrayList<>(List.of("Thali", "Biryani")); }
class Waiter {
    void printAll(BreakfastMenu b, LunchMenu l) {
        for (int i = 0; i < b.items.length; i++)                  // knows: it's an array
            System.out.println(b.items[i]);
        for (int i = 0; i < l.items.size(); i++)                  // knows: it's a list
            System.out.println(l.items.get(i));
    }
}
public class Main {
    public static void main(String[] args) {
        new Waiter().printAll(new BreakfastMenu(), new LunchMenu());
    }
}

Output (real):

Main.java:6: error: cannot find symbol
        for (int i = 0; i < b.items.length; i++)                  // knows: it's an array
                                   ^
  symbol:   variable length
  location: variable items of type List<String>
Main.java:7: error: array required, but List<String> found
            System.out.println(b.items[i]);
                                      ^
2 errors

Why it failed

  • The client (the code that uses an object, here Waiter) knows how each collection stores its items.
  • Changing the storage means editing every client that walks it.
  • A new kind of menu (desserts in a sorted set) means writing yet another loop.
  • The inside of the collection has leaked out. Keeping the inside private is information hiding (episode 6), and this code breaks it.

We want what the remote gives us: ask the collection for a walker, and every walker has the same two buttons.

3. The fix: Iterable and Iterator

Java already has the two interfaces we need, in java.util and java.lang:

public interface Iterator<E> {      // the walker
    boolean hasNext();              // is there another item?
    E next();                       // give it to me and move on
    default void remove() { ... }   // optional: delete the item next() just returned
}
public interface Iterable<T> {      // anything that can be walked
    Iterator<T> iterator();         // hand out a fresh walker
    default void forEach(Consumer<? super T> action) { ... }
}
import java.util.*;
class BreakfastMenu implements Iterable<String> {                 // the aggregate
    private final String[] items = {"Poha", "Upma", "Idli"};      // hidden: an array
    public Iterator<String> iterator() {
        return new Iterator<String>() {                           // a custom iterator
            private int i = 0;                                    // where am I?
            public boolean hasNext() { return i < items.length; }
            public String next() { return items[i++]; }
        };
    }
}
class LunchMenu implements Iterable<String> {
    private final List<String> items = new ArrayList<>(List.of("Thali", "Biryani"));
    public Iterator<String> iterator() { return items.iterator(); }   // reuse the list's
}
class Waiter {
    void print(Iterable<String> menu) {                           // knows NOTHING inside
        Iterator<String> it = menu.iterator();
        while (it.hasNext()) System.out.println("  " + it.next());
    }
}
public class Main {
    public static void main(String[] args) {
        Waiter w = new Waiter();
        w.print(new BreakfastMenu());
        w.print(new LunchMenu());
        w.print(new TreeSet<>(Set.of("Kulfi", "Jalebi")));        // a sorted set, too
    }
}

Output (real):

  Poha
  Upma
  Idli
  Thali
  Biryani
  Jalebi
  Kulfi

What each part does:

  • BreakfastMenu implements Iterable<String>: its array is now private, so no other class can touch it. Its iterator() returns a custom iterator: our own class that implements Iterator.
  • That custom iterator is an anonymous class: a class with no name, written right where it is needed (new Iterator<String>() { ... }). It remembers one number, i, its position in the array. hasNext() is true while i < items.length; next() returns items[i] and then moves i forward.
  • LunchMenu stores its items in an ArrayList, which can already walk itself, so it simply returns items.iterator().
  • Waiter.print(Iterable<String> menu) knows nothing about arrays or lists. It asks for an iterator and loops while (it.hasNext()) ... it.next().
  • The same method walks a TreeSet (a set that keeps its items sorted), so Jalebi comes before Kulfi.

If the chef changes breakfast to a list tomorrow, only BreakfastMenu changes. The waiter compiles untouched.

4. It has a name: the Iterator pattern

   Waiter (client) ──asks for──▶ Iterable<T>  (aggregate)  - - creates - -▶  Iterator<T> (iterator)
                                  + iterator()                               + hasNext()
                                       ▲                                     + next()
                                       ┊ implements                                ▲ implements
                                 BreakfastMenu  ◀────────── walks ──────────  menu iterator
                                 (concrete aggregate)                         (concrete iterator, field i)
Role In our code Job
Client Waiter Walks items without knowing the storage
Aggregate Iterable<String> Hands out an iterator
Iterator Iterator<String> hasNext() and next()
Concrete aggregate BreakfastMenu, LunchMenu, TreeSet The real collections
Concrete iterator the anonymous class, ArrayList's iterator Knows how to walk that one storage

The classic intent (SourceMaking): "Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation." Because the walking is its own object, every collection can be walked the same way: polymorphic traversal.

Each iterator keeps its own position, so two waiters can walk the same menu at the same time with two iterators, and never disturb each other.

5. The for-each loop and the iterator contract

The for-each loop (for (String item : menu)) works on anything that implements Iterable. The compiler turns it into:

for (Iterator<String> it = menu.iterator(); it.hasNext(); ) {
    String item = it.next();
    ...
}

The iterator contract is the promise every iterator makes. The key rule: when there are no more elements, next() throws NoSuchElementException. Our first custom iterator forgot it:

import java.util.*;
class BreakfastMenu implements Iterable<String> {
    private final String[] items = {"Poha", "Upma", "Idli"};
    public Iterator<String> iterator() {
        return new Iterator<String>() {
            private int i = 0;
            public boolean hasNext() { return i < items.length; }
            public String next() { return items[i++]; }           // no check!
        };
    }
}
public class Main {
    public static void main(String[] args) {
        BreakfastMenu menu = new BreakfastMenu();
        for (String item : menu) System.out.println(item);        // for-each just works
        Iterator<String> it = menu.iterator();
        for (int n = 0; n < 4; n++) System.out.println(it.next()); // one too many
    }
}

Output (real):

Poha
Upma
Idli
Poha
Upma
Idli
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    at BreakfastMenu$1.next(Main.java:8)
    at BreakfastMenu$1.next(Main.java:5)
    at Main.main(Main.java:17)

ArrayIndexOutOfBoundsException leaks the inside again: the caller learns there is an array. The fix checks first:

import java.util.*;
class BreakfastMenu implements Iterable<String> {
    private final String[] items = {"Poha", "Upma", "Idli"};
    public Iterator<String> iterator() {
        return new Iterator<String>() {
            private int i = 0;
            public boolean hasNext() { return i < items.length; }
            public String next() {
                if (!hasNext()) throw new NoSuchElementException("menu has ended");
                return items[i++];
            }
        };
    }
}
public class Main {
    public static void main(String[] args) {
        BreakfastMenu menu = new BreakfastMenu();
        for (String item : menu) System.out.println(item);        // for-each just works
        Iterator<String> it = menu.iterator();
        for (int n = 0; n < 4; n++) System.out.println(it.next()); // one too many
    }
}

Output (real):

Poha
Upma
Idli
Poha
Upma
Idli
Exception in thread "main" java.util.NoSuchElementException: menu has ended
    at BreakfastMenu$1.next(Main.java:9)
    at BreakfastMenu$1.next(Main.java:5)
    at Main.main(Main.java:20)

Callers should still call hasNext() before next(), but if they don't, the failure is the standard, honest one.

6. The trap: changing a list while walking it

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> orders = new ArrayList<>(
            List.of("Poha", "CANCELLED Chai", "Thali", "Dosa"));
        for (String o : orders) {
            if (o.startsWith("CANCELLED")) orders.remove(o);       // change it mid-walk
        }
        System.out.println(orders);
    }
}

Output (real):

Exception in thread "main" java.util.ConcurrentModificationException
    at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1095)
    at java.base/java.util.ArrayList$Itr.next(ArrayList.java:1049)
    at Main.main(Main.java:6)

ConcurrentModificationException means "the collection was changed while it was being walked". The for-each loop hides an iterator; orders.remove(o) changed the list behind that iterator's back. ArrayList's iterator notices the structural change (its internal modification count no longer matches, checked in checkForComodification) and stops at once instead of skipping or misreading an order.

That is a fail-fast iterator: it fails immediately and loudly when the collection is changed under it, other than through the iterator itself. The ArrayList javadoc says its iterators "are fail-fast" and that "Fail-fast iterators throw ConcurrentModificationException on a best-effort basis." So treat the exception as a bug alarm, never as something your program relies on.

The fix: remove through the iterator, or use removeIf

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> orders = new ArrayList<>(
            List.of("Poha", "CANCELLED Chai", "Thali", "Dosa"));
        Iterator<String> it = orders.iterator();
        while (it.hasNext()) {
            if (it.next().startsWith("CANCELLED")) it.remove();     // through the iterator
        }
        System.out.println(orders);
        orders.removeIf(o -> o.equals("Dosa"));                   // or: removeIf
        System.out.println(orders);
    }
}

Output (real):

[Poha, Thali, Dosa]
[Poha, Thali]

Iterator.remove() deletes the item that next() just returned and keeps the iterator in step. Collection.removeIf(condition) does the whole loop for you.

Puzzle (homework 4). In the example above, remove "Thali" (the second-last item) inside the for-each instead of the cancelled chai, and the program prints no exception at all:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> orders = new ArrayList<>(List.of("Poha", "CANCELLED Chai", "Thali", "Dosa"));
        for (String o : orders) {
            if (o.equals("Thali")) orders.remove(o);   // the second-last item
        }
        System.out.println(orders);
    }
}

Output (real):

[Poha, CANCELLED Chai, Dosa]

Why? After removing Thali the list has 3 items and the hidden iterator's cursor is already 3, so hasNext() (cursor != size) returns false and the loop ends before next() runs the check. Dosa is never visited. That's exactly why the docs say "best-effort": never depend on the exception.

7. Fail-safe (snapshot) iterators

A thread is a separate line of work running at the same time inside one program. When other threads really do add items while you walk, java.util.concurrent has collections whose iterators never throw:

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class Main {
    public static void main(String[] args) {
        List<String> orders = new CopyOnWriteArrayList<>(List.of("Poha", "Thali"));
        for (String o : orders) {                                 // walks a snapshot
            System.out.println("cooking " + o);
            if (o.equals("Poha")) orders.add("Chai");             // new order mid-walk
        }
        System.out.println("now: " + orders);
    }
}

Output (real):

cooking Poha
cooking Thali
now: [Poha, Thali, Chai]

Every change to a CopyOnWriteArrayList makes a fresh copy of its internal array. Its iterator walks a snapshot: a frozen copy of the list from the moment the iterator was created. The javadoc says this iterator "is guaranteed not to throw ConcurrentModificationException", and that "Element-changing operations on iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException." People call this style fail-safe.

Fail-fast Fail-safe (snapshot)
Examples ArrayList, HashMap, HashSet, LinkedList CopyOnWriteArrayList, CopyOnWriteArraySet
Walks the live collection a snapshot copy
Changed mid-walk (not via iterator) ConcurrentModificationException (best-effort) no exception; the loop never sees the change
iterator.remove() supported UnsupportedOperationException
Cost none extra copies the whole array on every write
Use for everyday code many reads, rare writes, several threads (e.g. listener lists)

(Other concurrent collections such as ConcurrentHashMap have weakly consistent iterators: they never throw, and may or may not show changes made during the walk.)

8. Internal vs external iteration, and the Spliterator

import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> menu = List.of("Poha", "Upma", "Idli", "Thali", "Dosa", "Chai");
        Iterator<String> it = menu.iterator();                    // external: YOU drive
        while (it.hasNext()) { String s = it.next(); if (s.equals("Idli")) break; }
        menu.forEach(s -> System.out.print(s + " "));              // internal: list drives
        System.out.println();
        Spliterator<String> right = menu.spliterator();
        Spliterator<String> left = right.trySplit();               // split in two halves
        left.forEachRemaining(s -> System.out.print("[L] " + s + " "));
        System.out.println();
        right.tryAdvance(s -> System.out.println("[R] first: " + s));
    }
}

Output (real):

Poha Upma Idli Thali Dosa Chai 
[L] Poha [L] Upma [L] Idli 
[R] first: Thali
  • External iteration: you hold the iterator and drive it (hasNext/next), so you can stop early with break.
  • Internal iteration: you hand the collection a small piece of code, a lambda (a short nameless function, s -> System.out.print(s + " ")), and the collection drives the loop: forEach. Less code, and the collection may walk itself in the best way.
  • Spliterator ("splittable iterator"): the javadoc calls it "An object for traversing and partitioning elements of a source." trySplit() hands part of the items to a new spliterator (for an ArrayList, the first half), so two workers can process two halves at once; parallel streams use this. tryAdvance(action) processes one item if one remains and returns true, else false. forEachRemaining(action) processes all that remain.

9. When to write your own iterator (and when not)

Use it when Skip it when
You build your own collection (menu, playlist, tree, ring buffer) and want to hide its storage A plain List already does the job: return Collections.unmodifiableList(list) or List.copyOf(list)
There are several ways to walk it (tree: depth-first, level by level): one iterator each You only need one loop in one place
You want for-each to work: implement Iterable

Common mistakes

Mistake What you see Why Fix
Client loops over a collection's inside error: array required, but List<String> found / cannot find symbol ... variable length Storage leaked to the client Iterable + Iterator
list.remove(x) inside a for-each java.util.ConcurrentModificationException List changed behind the hidden iterator it.remove() or removeIf
Custom next() with no end check ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 Breaks the iterator contract if (!hasNext()) throw new NoSuchElementException()
Calling next() twice per loop Items skipped, or NoSuchElementException Each next() moves forward Store it.next() in a variable once
Expecting a snapshot iterator to see new items No error: item not visited Fail-safe walks a frozen copy Know which iterator you have
it.remove() on a CopyOnWriteArrayList iterator UnsupportedOperationException Snapshot iterators can't change the list list.remove(x) / removeIf

Mini project: a playlist with a shuffle iterator

A Playlist that can be walked in order (for-each) and in a shuffled order, each walk with its own iterator.

import java.util.*;
class Playlist implements Iterable<String> {
    private final List<String> songs = new ArrayList<>();
    void add(String s) { songs.add(s); }
    public Iterator<String> iterator() { return Collections.unmodifiableList(songs).iterator(); }
    Iterator<String> shuffled(long seed) {
        List<Integer> order = new ArrayList<>();
        for (int i = 0; i < songs.size(); i++) order.add(i);
        Collections.shuffle(order, new Random(seed));          // a fixed seed: the same shuffle every run
        return new Iterator<String>() {
            private int k = 0;
            public boolean hasNext() { return k < order.size(); }
            public String next() {
                if (!hasNext()) throw new NoSuchElementException("playlist ended");
                return songs.get(order.get(k++));
            }
        };
    }
}
public class Main {
    public static void main(String[] args) {
        Playlist p = new Playlist();
        for (String s : List.of("Song A", "Song B", "Song C", "Song D")) p.add(s);
        for (String s : p) System.out.print(s + " | ");
        System.out.println();
        Iterator<String> sh = p.shuffled(42);
        while (sh.hasNext()) System.out.print(sh.next() + " | ");
        System.out.println();
    }
}

Output (real):

Song A | Song B | Song C | Song D | 
Song D | Song B | Song A | Song C | 

Practice

1. Add remove() to the BreakfastMenu iterator. Since an array can't shrink, store the menu in an ArrayList inside, and make remove() delete the item next() just returned. Calling remove() twice in a row, or before next(), must throw IllegalStateException.

Answer
import java.util.*;
class BreakfastMenu implements Iterable<String> {
    private final List<String> items = new ArrayList<>(List.of("Poha", "Upma", "Idli"));
    public Iterator<String> iterator() {
        return new Iterator<String>() {
            private int i = 0; private boolean canRemove = false;
            public boolean hasNext() { return i < items.size(); }
            public String next() {
                if (!hasNext()) throw new NoSuchElementException();
                canRemove = true; return items.get(i++);
            }
            public void remove() {
                if (!canRemove) throw new IllegalStateException("call next() first");
                items.remove(--i); canRemove = false;          // step back: the list shifted left
            }
        };
    }
}
public class Main {
    public static void main(String[] args) {
        BreakfastMenu m = new BreakfastMenu();
        Iterator<String> it = m.iterator();
        while (it.hasNext()) if (it.next().equals("Upma")) it.remove();
        for (String s : m) System.out.println(s);
        Iterator<String> it2 = m.iterator();
        it2.remove();
    }
}

Output (real):

Poha
Idli
Exception in thread "main" java.lang.IllegalStateException: call next() first
    at BreakfastMenu$1.remove(Main.java:13)
    at Main.main(Main.java:26)

2. Write an iterator that walks a binary tree depth-first (root, then left subtree, then right subtree) using a stack, without recursion.

Answer
import java.util.*;
class Node {
    final String name; final Node left, right;
    Node(String name, Node left, Node right) { this.name = name; this.left = left; this.right = right; }
}
class Tree implements Iterable<String> {
    private final Node root;
    Tree(Node root) { this.root = root; }
    public Iterator<String> iterator() {
        Deque<Node> stack = new ArrayDeque<>();
        if (root != null) stack.push(root);
        return new Iterator<String>() {
            public boolean hasNext() { return !stack.isEmpty(); }
            public String next() {
                if (!hasNext()) throw new NoSuchElementException();
                Node n = stack.pop();
                if (n.right != null) stack.push(n.right);      // right first, so left comes out first
                if (n.left != null) stack.push(n.left);
                return n.name;
            }
        };
    }
}
public class Main {
    public static void main(String[] args) {
        Tree t = new Tree(new Node("Menu",
            new Node("Breakfast", new Node("Poha", null, null), new Node("Idli", null, null)),
            new Node("Lunch", new Node("Thali", null, null), null)));
        for (String s : t) System.out.print(s + " ");
        System.out.println();
    }
}

Output (real):

Menu Breakfast Poha Idli Lunch Thali 

3. Write a Range class so that for (int i : new Range(3, 7)) prints 3 4 5 6.

Answer
import java.util.*;
class Range implements Iterable<Integer> {
    private final int from, to;                                // to is exclusive
    Range(int from, int to) { this.from = from; this.to = to; }
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            private int cur = from;
            public boolean hasNext() { return cur < to; }
            public Integer next() {
                if (!hasNext()) throw new NoSuchElementException();
                return cur++;
            }
        };
    }
}
public class Main {
    public static void main(String[] args) {
        for (int i : new Range(3, 7)) System.out.print(i + " ");
        System.out.println();
    }
}

Output (real):

3 4 5 6 

4. Explain the puzzle in section 6: why does removing the second-last item inside a for-each print no exception?

Answer

ArrayList's iterator checks for changes inside next(), not inside hasNext(). After removing the second-last item, the size drops to the cursor's value, hasNext() returns false, the loop ends, and next() (with its check) never runs. The last item is silently skipped. Fail-fast is best-effort.

Quick quiz

List<String> l = new ArrayList<>(
    List.of("Chai", "Poha", "Dosa"));
for (String s : l)
    if (s.equals("Chai")) l.remove(s);

What happens? (a) l becomes [Poha, Dosa] (b) ConcurrentModificationException (c) Compile error (d) Infinite loop

Answer

(b) ConcurrentModificationException. The list is changed through l.remove while the for-each's hidden iterator walks it, so the next next() fails fast. Use it.remove() or l.removeIf(s -> s.equals("Chai")).

Interview questions

  1. What is the Iterator pattern? A behavioural pattern that gives a way to access the elements of a collection one by one without exposing how it is stored.
  2. Participants? Client, aggregate (Iterable), iterator (Iterator), concrete aggregate, concrete iterator.
  3. Iterator vs Iterable? Iterable is the collection side (iterator() hands out walkers); Iterator is the walker (hasNext, next, optional remove). For-each needs an Iterable.
  4. What does next() do at the end? Throws NoSuchElementException (the contract).
  5. What is a fail-fast iterator? One that throws ConcurrentModificationException (best-effort) if the collection is structurally changed during iteration other than through the iterator. ArrayList, HashMap.
  6. Fail-safe? It iterates over a snapshot (CopyOnWriteArrayList) and never throws CME, but doesn't see changes and can't remove.
  7. How do you remove elements while iterating? Iterator.remove(), removeIf, or collect to remove and remove afterwards.
  8. External vs internal iteration? External: the caller drives with hasNext/next. Internal: the collection drives (forEach, streams) and the caller passes a lambda.
  9. What is a Spliterator? An iterator that can also split its elements (trySplit) so parallel streams can process parts at once; tryAdvance processes one element.
  10. Why might a class return an iterator instead of its list? To hide the storage and prevent callers from modifying it; the class can change its internals freely.

Glossary

Term Meaning, with an example
Behavioural pattern A design pattern about how objects share work and talk to each other. Iterator, Observer, Chain of Responsibility
Aggregate (collection) An object that holds many items. A menu, an ArrayList, a TreeSet
Iterator An object that walks a collection one item at a time. The TV remote's Next button
Iterator pattern Access a collection's items one by one without exposing how it is stored
Iterator interface java.util.Iterator<E>: hasNext(), next(), optional remove()
Iterable java.lang.Iterable<T>: one method, iterator(). Anything Iterable works in a for-each loop
hasNext() Returns true if another item is waiting. "Any more channels?"
next() Returns the next item and moves forward; throws NoSuchElementException at the end
remove() (iterator) Deletes the item next() just returned, safely, during the walk
for-each loop for (String s : menu): the compiler turns it into a hasNext/next loop on menu.iterator()
Client The code that uses an object. Waiter
Custom iterator Your own class that implements Iterator. The menu's array walker
Anonymous class A class with no name, written where it's needed: new Iterator<String>() { ... }
Iterator contract The promises an iterator keeps: next() past the end throws NoSuchElementException; remove() before next() throws IllegalStateException
NoSuchElementException The standard exception for "no more elements"
Polymorphic traversal One loop that walks any kind of collection through the same interface
Information hiding Keeping an object's internals private so others can't depend on them (episode 6)
ConcurrentModificationException Thrown (best-effort) when a collection is changed while an iterator walks it, other than through that iterator
Structural modification A change to a collection's size or shape: add, remove. Setting an element is not structural
Fail-fast iterator Fails immediately when the collection changes under it. ArrayList's iterator
Fail-safe iterator Never fails during iteration because it walks a snapshot. CopyOnWriteArrayList's iterator
Snapshot A frozen copy of data from one moment
Weakly consistent iterator Never throws CME and may or may not show changes made during the walk. ConcurrentHashMap
Thread A separate line of work running at the same time inside one program
CopyOnWriteArrayList A thread-safe list in java.util.concurrent that copies its array on every write
removeIf collection.removeIf(condition): removes every element that matches, safely
External iteration The caller drives the loop with hasNext/next; can break early
Internal iteration The collection drives the loop and calls your lambda: list.forEach(s -> ...)
Lambda A short nameless function: s -> System.out.print(s)
Spliterator "An object for traversing and partitioning elements of a source"; trySplit splits off part, tryAdvance processes one element
TreeSet A set that keeps its items sorted

Summary

  • A client that loops over a collection's inside breaks when the storage changes (array required, but List<String> found).
  • Iterator pattern: the collection (an Iterable) hands out an Iterator with hasNext() and next(), so one loop walks an array, a list or a set.
  • Implement Iterable and for-each works; keep the contract: NoSuchElementException at the end.
  • Everyday iterators are fail-fast: change a collection mid-walk only through it.remove() or with removeIf, or you get ConcurrentModificationException.
  • Fail-safe (snapshot) iterators never throw but never see changes; they cost a copy per write.
  • External vs internal iteration (forEach); a Spliterator can split work for parallel streams.

Next episode: The Mediator pattern: when every object talks to every other object, put one hub in the middle.