Java.Collections.Compare Iterator and ListIterator.

FeatureIteratorListIterator
Applicable toAll Collection typesOnly 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 sinceJDK 1.2JDK 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 CaseUse
Simple forward iteration over any collectionIterator
Need to traverse both directions in a listListIterator
Need to insert, update, or delete elements while iterating a listListIterator
Working with Set, Queue, or general CollectionIterator

💬 Summary

  • Iterator = Simple, forward-only, works on any collection, minimal operations.
  • ListIterator = Advanced, bidirectional, list-specific, supports add/set/remove with index awareness.
This entry was posted in Без рубрики. Bookmark the permalink.