Here we will discuss the differences between Iterator and ListIterator. Both of these interfaces are used for traversing but still there are few differences in the way they can be used for traversing a collection. I would recommend you to go through the following tutorials to understand these interfaces better before going through the differences.
Java – Iterator
Java – ListIterator
Iterator vs ListIterator
1) Iterator is used for traversing List
and Set
both.
We can use ListIterator to traverse List
only, we cannot traverse Set
using ListIterator.
2) We can traverse in only forward direction using Iterator.
Using ListIterator, we can traverse a List in both the directions (forward and Backward).
3) We cannot obtain indexes while using Iterator
We can obtain indexes at any point of time while traversing a list using ListIterator. The methods nextIndex() and previousIndex() are used for this purpose.
4) We cannot add element to collection while traversing it using Iterator, it throws ConcurrentModificationException when you try to do it.
We can add element at any point of time while traversing a list using ListIterator.
5) We cannot replace the existing element value when using Iterator.
By using set(E e) method of ListIterator we can replace the last element returned by next() or previous() methods.
6) Methods of Iterator:
- hasNext()
- next()
- remove()
Methods of ListIterator:
- add(E e)
- hasNext()
- hasPrevious()
- next()
- nextIndex()
- previous()
- previousIndex()
- remove()
- set(E e)
Ajit says
This article helped me. Nice and simple. To the point. I really appreciate that you shared this info :)
Nikhil Sane says
Hi Chaitanya,
Your Statement “We can add element at any point of time while traversing a list using ListIterator”.
I have tried to add element to List while traversing the list using List Iterator. It is gave me below error.
Error: Exception in thread “main” java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at ArrayListExample.main(ArrayListExample.java:19)
mani kumar says
you have to use concurrenthashmap in case of maps and CopyOnWriteArrayList in case of list to avoid that exception