Lesson Completion
Back to course

Iterators: Traversing Collections Safely

Intermediate
20 minutesβ˜…4.8Java

1. The Hook (The "Byte-Sized" Intro)

In a Nutshell: Iterator provides a standard way to traverse collections. ListIterator adds bidirectional traversal for Lists. Iterators are fail-fast (throw ConcurrentModificationException if collection modified during iteration). Use iterators when you need to remove elements during traversalβ€”for-each loops don't support removal.

Think of museum tour guide. Iterator = guide leading you room-by-room (hasNext(), next()). If someone rearranges exhibits mid-tour? Tour fails (fail-fast)!


2. Conceptual Clarity (The "Simple" Tier)

πŸ’‘ The Analogy: The Book Cursor

  • Iterator: Bookmark moving forward only
  • ListIterator: Bookmark that can flip backward too
  • Fail-fast: Book pages change while reading β†’ error!

3. Technical Mastery (The "Deep Dive")

Iterator Methods

java
interface Iterator<E> { boolean hasNext(); // More elements? E next(); // Get next element void remove(); // Remove current element }

ListIterator (extends Iterator)

java
interface ListIterator<E> extends Iterator<E> { boolean hasPrevious(); // Can go backward? E previous(); // Get previous int nextIndex(); // Index of next void add(E e); // Insert element void set(E e); // Replace current }

4. Interactive & Applied Code

java
import java.util.*; public class IteratorDemo { public static void main(String[] args) { // ITERATOR: Forward traversal List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D")); Iterator<String> it = list.iterator(); while (it.hasNext()) { String item = it.next(); System.out.print(item + " "); if (item.equals("B")) { it.remove(); // βœ… Safe removal during iteration } } System.out.println("\nAfter removal: " + list); // [A, C, D] // FAIL-FAST behavior try { Iterator<String> it2 = list.iterator(); while (it2.hasNext()) { String item = it2.next(); list.add("X"); // ❌ Modifying collection directly! } } catch (ConcurrentModificationException e) { System.out.println("❌ Fail-fast: " + e.getClass().getSimpleName()); } // LISTITERATOR: Bidirectional ListIterator<String> lit = list.listIterator(); System.out.print("Forward: "); while (lit.hasNext()) { System.out.print(lit.next() + " "); } System.out.print("\nBackward: "); while (lit.hasPrevious()) { System.out.print(lit.previous() + " "); } // Modifying during iteration ListIterator<String> lit2 = list.listIterator(); while (lit2.hasNext()) { String item = lit2.next(); if (item.equals("C")) { lit2.set("C_MODIFIED"); // βœ… Replace current lit2.add("INSERTED"); // βœ… Insert after current } } System.out.println("\nModified: " + list); } }

5. The Comparison & Decision Layer

Featurefor-eachIteratorListIterator
DirectionForward onlyForward onlyBoth
RemoveβŒβœ…βœ…
AddβŒβŒβœ…
IndexβŒβŒβœ…

6. The "Interview Corner" (The Edge)

The "Killer" Interview Question: "What's the difference between fail-fast and fail-safe iterators?" Answer:

  • Fail-fast (ArrayList, HashMap): Throws ConcurrentModificationException if collection modified during iteration. Detects via modCount field.
  • Fail-safe (CopyOnWriteArrayList, ConcurrentHashMap): Doesn't throw exception. Works on copy or allows concurrent modifications.

Trade-off: Fail-safe = thread-safe but higher memory/performance cost.

Pro-Tip: Remove during iteration:

java
// ❌ BAD: ConcurrentModificationException for (String s : list) { if (s.equals("remove-me")) list.remove(s); } // βœ… GOOD: Use iterator.remove() Iterator<String> it = list.iterator(); while (it.hasNext()) { if (it.next().equals("remove-me")) it.remove(); } // βœ… BEST (Java 8+): removeIf list.removeIf(s -> s.equals("remove-me"));

Topics Covered

Java FundamentalsData Structures

Tags

#java#collections#list#set#map#arraylist#hashmap

Last Updated

2025-02-01