Difference between Iterator and Listiterator?
Solution 1:
The differences are listed in the Javadoc for ListIterator
You can
- iterate backwards
- obtain the iterator at any point.
- add a new value at any point.
- set a new value at that point.
Solution 2:
There are two differences:
-
We can use Iterator to traverse Set and List and also Map type of Objects. While a ListIterator can be used to traverse for List-type Objects, but not for Set-type of Objects.
That is, we can get a Iterator object by using Set and List, see here:
By using Iterator we can retrieve the elements from Collection Object in forward direction only.
Methods in Iterator:
hasNext()
next()
remove()
Iterator iterator = Set.iterator(); Iterator iterator = List.iterator();
-
But we get ListIterator object only from the List interface, see here:
where as a ListIterator allows you to traverse in either directions (Both forward and backward). So it has two more methods like
hasPrevious()
andprevious()
other than those of Iterator. Also, we can get indexes of the next or previous elements (usingnextIndex()
andpreviousIndex()
respectively )Methods in ListIterator:
- hasNext()
- next()
- previous()
- hasPrevious()
- remove()
- nextIndex()
- previousIndex()
ListIterator listiterator = List.listIterator();
i.e., we can't get ListIterator object from Set interface.
Reference : - What is the difference between Iterator and ListIterator ?