ListIterator in Java

In Java there is an Iterator interface which provides an iterator over a collection (List, Set etc.) but there is another interface ListIterator in Java which provides an iterator exclusively for lists (ArrayList, LinkedList, CopyOnWriteArrayList etc.).

While iterator can only move forward, ListIterator in Java provides functionality to traverse the List in either direction; forward or backward, which is one of the difference between Iterator and ListIterator in Java. Other differences are as follows.

  1. Both of these interfaces have remove() method to safely remove an element from List after the iterator is created but ListIterator has an add() method too.
  2. ListIterator also has a set() method to change the element while iterating a List.

No current element in ListIterator

A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). Following image shows the possible cursor positions for a list of length n.

ListIterator in Java

Java ListIterator methods

ListIterator interface in Java provides the following methods-

  1. add(E e) – Inserts the specified element into the list.
  2. hasNext() – Returns true if this list iterator has more elements when traversing the list in the forward direction.
  3. hasPrevious() – Returns true if this list iterator has more elements when traversing the list in the reverse direction.
  4. next() – Returns the next element in the list and advances the cursor position.
  5. nextIndex() – Returns the index of the element that would be returned by a subsequent call to next().
  6. previous() – Returns the previous element in the list and moves the cursor position backwards.
  7. previousIndex() – Returns the index of the element that would be returned by a subsequent call to previous().
  8. remove() – Removes from the list the last element that was returned by next() or previous().
  9. set(E e) – Replaces the last element returned by next() or previous() with the specified element.

Java ListIterator example with bi-directional traversal

Output

Example using add() and set() method of ListIterator

output

That’s all for the topic ListIterator in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.