Both Iterator and ListIterator are used to traverse collections in Java, but they differ in their functionality and scope.
Iterator
- Definition:
- An
Iteratoris used to traverse elements of a collection (e.g.,Set,List) in a forward direction.
- An
- Key Features:
- Can traverse only forward.
- Allows removal of elements using
remove().
- Supported Methods:
hasNext(): Checks if there are more elements.next(): Returns the next element.remove(): Removes the last element returned by the iterator.
- Use Case:
- Suitable for general-purpose iteration over any collection.
- Example:
List<String> list = Arrays.asList("A", "B", "C");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
ListIterator
- Definition:
- A
ListIteratoris a specialized iterator used to traverseListcollections in both forward and backward directions.
- A
- Key Features:
- Can traverse both forward and backward.
- Allows addition, removal, and modification of elements during iteration.
- Supported Methods:
- All methods from
Iterator. hasPrevious(): Checks if there are elements before the current position.previous(): Returns the previous element.add(E e): Adds an element to the list.set(E e): Replaces the last element returned bynext()orprevious().
- All methods from
- Use Case:
- Best for use cases where bidirectional traversal or modification of elements is required.
- Example:
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
ListIterator<String> listIterator = list.listIterator();
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
Key Differences
| Aspect | Iterator | ListIterator |
|---|---|---|
| Traversal | Forward only. | Forward and backward. |
| Modification | Can remove elements. | Can add, remove, or modify elements. |
| Applicable To | All collections. | Only List collections. |
| Additional Methods | None. | hasPrevious(), previous(), etc. |
Summary
- Use Iterator for simple forward traversal of any collection.
- Use ListIterator when working with
Listcollections that require bidirectional traversal or in-place modifications.