ListIterator is a powerful iterator available in the Java Collection Framework. It allows bidirectional traversal of a List and supports element modification during iteration.
Use the buttons below to see how the cursor sits between elements.
A ListIterator is obtained using the listIterator() method of a List. It extends the Iterator interface with additional methods.
// Creating a ListIterator from a List
ListIterator<String> it = list.listIterator();
// Demonstrating forward and backward traversal using ListIterator
import java.util.*;
class ListIteratorDemo {
public static void main(String[] args) {
List names = new ArrayList<>();
names.add("Java");
names.add("Python");
names.add("C++");
ListIterator li = names.listIterator();
while(li.hasNext()) {
System.out.println(li.next());
}
while(li.hasPrevious()) {
System.out.println(li.previous());
}
}
}
Java
Python
C++
C++
Python
Java
The iterator first moves forward using hasNext() and then backward using hasPrevious().
add() method of ListIteratorset()