• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

Every collection needs a way to traverse its elements, but different data structures store elements differently — arrays store contiguously, linked lists store with pointers, trees store with child references. A uniform traversal interface is needed that works regardless of internal structure.

Core Idea

The Iterator interface provides a standard way to traverse a collection: hasNext() checks for remaining elements, next() returns the next element, and remove() (optional) removes the last returned element. The Iterable interface enables the enhanced for-each loop, which uses an iterator under the hood.

How It Works

When iterator() is called on a collection, a concrete iterator instance is returned. For ArrayList, this is a cursor that walks the backing array. For LinkedList, it follows node pointers. The iterator tracks its position and detects structural modification to the collection (fail-fast behavior).

Visual Explanation

java_iterator List ArrayList [A, B, C, D] Iter Iterator cursor=0 List->Iter Step1 hasNext()→true next()→A cursor→1 Iter->Step1 Step2 hasNext()→true next()→B cursor→2 Step1->Step2 Step3 hasNext()→true next()→C cursor→3 Step2->Step3 Done hasNext()→false end Step3->Done

Semantic Network

semantic_iterator THIS Iterator COLL Collections THIS--COLL built from LOOP For-Each Loop THIS--LOOP builds into STREAM Streams THIS--STREAM related FAIL Fail-Fast Behavior THIS--FAIL builds into

Key Properties

  • Fail-fast: Throws ConcurrentModificationException if the collection is modified during iteration
  • for-each sugar: for (T item : collection) compiles to iterator-based loop
  • remove() is safe: Iterator.remove() modifies the collection without throwing
  • ListIterator: Extended interface for bidirectional traversal and index access

Connections

Edge Cases & Gotchas

  • No reset: An iterator is single-use — create a new one to traverse again
  • remove() before next(): IllegalStateException if next() hasn’t been called
  • Fail-fast is not guaranteed: It’s a best-effort detection mechanism, not a guarantee
  • LegacyEnumeration: Older collections (Vector, Hashtable) use Enumeration, not Iterator