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:
- 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 extendsIterator
and is specific to List implementations. It allows bidirectional traversal, which means you can traverse the list both forward and backward.
- Methods:
Iterator
provides a simpler set of methods compared toListIterator
. It has methods likehasNext()
,next()
, andremove()
.ListIterator
includes additional methods such ashasPrevious()
,previous()
,nextIndex()
,previousIndex()
,add()
, andset()
.
- Supported Collections:
Iterator
can be used to iterate over any collection that implements theIterable
interface, such asList
,Set
, andMap
.ListIterator
is specifically designed for Lists. It can be used to iterate over any List implementation, likeArrayList
,LinkedList
, etc.
- Usage:
Iterator
is obtained from theiterator()
method of a collection and is commonly used in a generic way for iterating over collections.ListIterator
is obtained from thelistIterator()
method of a List and is used when you need to traverse a List bidirectionally.
Here’s a simple example to illustrate the difference:
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.