← Back to Chapters

Java ListIterator

? Java ListIterator

? Quick Overview

ListIterator is a powerful iterator available in the Java Collection Framework. It allows bidirectional traversal of a List and supports element modification during iteration.

? Key Concepts

  • Works only with List implementations
  • Supports forward and backward traversal
  • Allows add, update, and remove operations
  • Available in java.util package

? Interactive Simulator

Use the buttons below to see how the cursor sits between elements.

 
State: Ready

? Syntax / Theory

A ListIterator is obtained using the listIterator() method of a List. It extends the Iterator interface with additional methods.

? View Code Example
// Creating a ListIterator from a List
ListIterator<String> it = list.listIterator();

? Code Example(s)

? View Code Example
// 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());
}
}
}

? Live Output / Explanation

Output

Java
Python
C++
C++
Python
Java

The iterator first moves forward using hasNext() and then backward using hasPrevious().

? Tips & Best Practices

  • Use ListIterator when you need bidirectional traversal
  • Avoid ConcurrentModificationException by using iterator methods
  • Prefer generics to maintain type safety

? Try It Yourself

  • Add elements using add() method of ListIterator
  • Replace elements using set()
  • Remove elements during iteration