ListIterator and Bidirectional Traversal
Use ListIterator to traverse lists forwards and backwards and modify elements during iteration.
ListIterator
ListIterator<T> extends Iterator<T> with backward traversal, index-based positioning, and the ability to add and replace elements during iteration.
ListIterator API
Additional methods beyond Iterator: hasPrevious(), previous(), nextIndex(), previousIndex(), set(), add().
import java.util.*;
List<String> list = new ArrayList<>(List.of("A", "B", "C", "D"));
ListIterator<String> lit = list.listIterator();
// Forward traversal
while (lit.hasNext()) {
System.out.print(lit.nextIndex() + ":" + lit.next() + " ");
}
// 0:A 1:B 2:C 3:D
System.out.println();
// Backward traversal
while (lit.hasPrevious()) {
System.out.print(lit.previousIndex() + ":" + lit.previous() + " ");
}
// 3:D 2:C 1:B 0:AAll lessons in this course
- The Iterable and Iterator Contracts
- Implementing a Custom Iterator
- ListIterator and Bidirectional Traversal
- Fail-Fast vs Fail-Safe Iterators