![]() |
VOOZH | about |
Iterator and ListIterator are interfaces provided by the Java Collection Framework to traverse collection elements one by one. Iterator is used for simple forward traversal of collections like List, Set, and Queue, whereas ListIteratorprovides advanced features such as backward traversal, element modification, and insertion in List collections.
Iterator is an interface available in the java.util package. It is mainly used to iterate through collection elements one at a time.
Syntax
Iterator<Integer> itr = list.iterator();
Elements using Iterator: 10 20 30
Explanation: In this example, the Iterator object traverses the ArrayList in forward direction using hasNext() and next() methods.
ListIterator is an interface that extends Iterator. It is used only for List collections and supports both forward and backward traversal.
Syntax
ListIterator<Integer> ltr = list.listIterator();
Forward Traversal: 1 2 3 Backward Traversal: 3 2 1
Explanation: In this example, ListIterator traverses the ArrayList in both forward and backward directions using next() and previous() methods.
Example: ListIterator can help to replace an element whereas Iterator cannot
Elements of ArrayList: 1 2 3 4 5 Now the ArrayList elements are: 80000 2 3 4 5
| Iterator | ListIterator |
|---|---|
| Traverses only in forward direction. | Traverses in both forward and backward directions. |
| Works with List, Set, Queue, etc. | Works only with List implementations. |
| Cannot add or replace elements. | Can add, replace, and remove elements. |
| Does not provide index information. | Provides nextIndex() and previousIndex() methods. |
Methods available: next(), hasNext(), remove() | Methods available: next(), previous(), add(), set() |
| Simpler and lightweight. | More powerful and feature-rich. |