ListIterator

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • ListIterator is a sub-interface of Iterator that is specific to List collections (like ArrayList and LinkedList).
  • Unlike a standard Iterator (which only moves forward), ListIterator can traverse the list in both directions (forward and backward).
  • It allows for item replacement and insertion during iteration.

Concept

Standard Iterator is limited: you can only ask “is there a next item?”, get the next item, and remove it.

Because List collections have a defined order and integer indexes, ListIterator unlocks much more power:

  • Bi-directional traversal: hasNext()/next() and hasPrevious()/previous().
  • Indexing: nextIndex() and previousIndex().
  • Modification: set(e) (replace the current item) and add(e) (insert a new item).

Examples

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class ListIteratorExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");
        
        ListIterator<String> lit = list.listIterator();
        
        // 1. Traverse Forward & Modify
        while (lit.hasNext()) {
            String item = lit.next();
            if (item.equals("B")) {
                lit.set("B-Updated"); // Replace B
                lit.add("X");         // Insert X right after B
            }
        }
        
        System.out.println("Forward pass: " + list); 
        // [A, B-Updated, X, C]
        
        // 2. Traverse Backward
        System.out.print("Backward pass: ");
        while (lit.hasPrevious()) {
            System.out.print(lit.previous() + " ");
        }
        // Output: C X B-Updated A
    }
}

Interview Questions

Q: Can you get a ListIterator for a HashSet?
A: No. ListIterator relies on the collection being an ordered sequence with an index. Sets and Maps do not have a defined index or bidirectional ordering. You can only call .listIterator() on classes that implement the List interface.

Q: If you use lit.add("X"), where exactly is the element inserted?
A: The element is inserted immediately before the element that would be returned by the next call to next(), and immediately after the element that would be returned by previous(). The cursor conceptually sits between elements.