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
| Feature | for-each | Iterator | ListIterator |
|---|---|---|---|
| Direction | Forward only | Forward only | Both |
| 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
ConcurrentModificationExceptionif collection modified during iteration. Detects viamodCountfield. - 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"));