Feature | Iterator | ListIterator |
---|---|---|
Applicable to | All Collection types | Only List types |
Direction of iteration | 🔁 Forward only | 🔁 Forward and backward |
Can remove elements? | ✅ Yes (remove() ) | ✅ Yes (remove() ) |
Can add elements? | ❌ No | ✅ Yes (add() ) |
Can replace elements? | ❌ No | ✅ Yes (set() ) |
Index awareness | ❌ No | ✅ Yes (nextIndex() , previousIndex() ) |
Available since | JDK 1.2 | JDK 1.2 |
🧪 Example: Iterator
List<String> list = List.of("A", "B", "C");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
✅ Can only go forward, and cannot modify (if using List.of()
, which is unmodifiable).
🧪 Example: ListIterator
List<String> list = new ArrayList<>(List.of("A", "B", "C"));
ListIterator<String> lit = list.listIterator();
while (lit.hasNext()) {
String val = lit.next();
if (val.equals("B")) {
lit.set("Beta"); // ✅ Replace
lit.add("Bravo"); // ✅ Insert after current
}
}
System.out.println(list); // [A, Beta, Bravo, C]
// You can go backward too!
while (lit.hasPrevious()) {
System.out.println(lit.previous());
}
🔄 Direction of Traversal
✅ Iterator
A → B → C
✅ ListIterator
Forward: A → B → C
Backward: C ← B ← A
🧠 When to use which?
Use Case | Use |
---|---|
Simple forward iteration over any collection | Iterator |
Need to traverse both directions in a list | ListIterator |
Need to insert, update, or delete elements while iterating a list | ListIterator |
Working with Set , Queue , or general Collection | Iterator |
💬 Summary
Iterator
= Simple, forward-only, works on any collection, minimal operations.ListIterator
= Advanced, bidirectional, list-specific, supports add/set/remove with index awareness.