What is the Difference Between Java.util.Iterator and java.util.ListIterator

Iterator : Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements

ListIterator : extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.

In Java, java.util.Iterator and java.util.ListIterator are both interfaces that belong to the java.util package and are used for iterating over collections, but there are some key differences between them:

  1. Direction of Iteration:
    • Iterator is a universal interface for iterating over collections, and it supports only forward direction, i.e., you can only move from the beginning to the end of the collection.
    • ListIterator is an interface that extends Iterator and is specific to List implementations. It allows bidirectional traversal, which means you can traverse the list both forward and backward.
  2. Methods:
    • Iterator provides a simpler set of methods compared to ListIterator. It has methods like hasNext(), next(), and remove().
    • ListIterator includes additional methods such as hasPrevious(), previous(), nextIndex(), previousIndex(), add(), and set().
  3. Supported Collections:
    • Iterator can be used to iterate over any collection that implements the Iterable interface, such as List, Set, and Map.
    • ListIterator is specifically designed for Lists. It can be used to iterate over any List implementation, like ArrayList, LinkedList, etc.
  4. Usage:
    • Iterator is obtained from the iterator() method of a collection and is commonly used in a generic way for iterating over collections.
    • ListIterator is obtained from the listIterator() method of a List and is used when you need to traverse a List bidirectionally.

Here’s a simple example to illustrate the difference:

java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class IteratorExample {
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
myList.add(“One”);
myList.add(“Two”);
myList.add(“Three”);

// Using Iterator
Iterator<String> iterator = myList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

// Using ListIterator
ListIterator<String> listIterator = myList.listIterator(myList.size());
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}

In the example above, the Iterator is used for forward iteration, while the ListIterator is used for backward iteration.