Difference between Iterator and ListIterator in java

In this post, we will see difference between Iterator and ListIterator in java. They are both used for traversal but it is good to point out differences between them.

Iterator vs ListIterator:

Parameter
Iterator
ListIterator
Traversal
Iterator can be used to traverse List,set, Queue
ListIterator can be used to traverse only List.
Traversal direction

Iterator can be traversed only in forward direction

ListIterator can be traverse in forward direction as well backward.
Adding elements while traversing
You can not add elements while traversing using Iterator. It will through ConcurrentModificationException
You can add elements while traversing using ListIterator.
Replacing existing elements 
You can not replace exisitng elements while traversing using Iterator.
You can replace exisitng elements while traversing using ListIterator using set(E e).
Accessing Index
You can not access index using Iterator
You can access index using ListIterator via nextIndex() or previousIndex methods

Example:

1. Country.java 

2. IterateListMain.java 
When you run above program, you will get following output:

Was this post helpful?

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *