John John - 1 month ago 15
Java Question

Difference between Iterator and Listiterator?

Iterator ite = Set.iterator();
Iterator ite = List.iterator();

ListIterator listite = List.listIterator();


We can use
Iterator
to traverse a
Set
or a
List
or a
Map
. But
ListIterator
can only be used to traverse a
List
, it can't traverse a
Set
. Why?

I know that the main difference is that with iterator we can travel in only one direction but with
ListIterator
we can travel both directions. Are there any other differences? And any advantages of
ListIterator
over
Iterator
?

Answer

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.
Comments