Video in progress

What is the Iterator pattern, and how does Java's for-each loop relate to it?

An Iterator gives you a way to walk through a collection's elements one by one without exposing its internal structure. In Java, for-each calls Iterable.iterator() and works through hasNext()/next().

📖 Answer

for (String name : names) {
    System.out.println(name);
}

The compiler turns this into roughly the following:

Iterator<String> it = names.iterator();
while (it.hasNext()) {
    String name = it.next();
    System.out.println(name);
}

That's why ArrayList, HashSet and LinkedList can be walked with one loop, even though their insides are completely different. If you implement Iterable<T> in your own class, it works in for-each too.

A trap worth knowing: if you call list.remove(x) inside a for-each, you'll often get a ConcurrentModificationException. The right ways are it.remove() or list.removeIf(...).