4 · Data & Collections · lesson 23 of 41

Iterators & Iterable

The contract behind for-each.

Java
Iterator<String> it = names.iterator();
while (it.hasNext()) {
    String n = it.next();
    if (n.isEmpty()) it.remove();  // safe removal
}
Key takeaways
  • ✓for-each unrolls to iterator().hasNext()/next().
  • ✓Modifying a collection during for-each throws ConcurrentModificationException.