ListIterator Interface In Collection Framework

ListIterator is most powerful cursor available in Java collection API. By using ListIterator we can move either to the forward direction or to the backward direction and hence ListIterator is bidirectional cursor, unlike Enumeration or Iterator cursor which are single direction cursor.

By using ListIterator we can perform both replacement & addition of new elements in underlying collection as well as can perform read & remove operations. Using Enumeration we were not able to perform remove operations for underlying collection and Using Iterator we were not able to perform replacement & addition operations.

We can create ListIterator object by using public ListIterator<E> listIterator() method present in List interface.

           

Methods of ListIterator Interface 

 

Methods For forward direction movement Description
public boolean hasNext() Returns true if this list iterator has more elements when traversing the list in the forward direction.
public E next() Returns the next element in the list and advances the cursor position.
public int nextIndex() Returns the index of the element that would be returned by a subsequent call to next()

Methods For backward direction movement Description
public boolean hasPrevious() Returns true if this list iterator has more elements when traversing the list in the reverse direction.
public E previous() Returns the previous element in the list and moves the cursor position backwards.
public int previousIndex() Returns the index of the element that would be returned by a subsequent call to previous()

Methods For Extra Capability Description
public void remove() Removes from the list the last element that was returned by next() or previous() (optional operation).
public void set(E new) Replaces the last element returned by next() or previous() with the specified element (optional operation).
public void add(E new) Inserts the specified element into the list (optional operation).

   

ListIterator example using ArrayList

Output:

Limitation Of ListIterator

  • ListIterator is the most powerful cursor, but its limitation is, it is applicable only for List interface implementing class object (cannot apply to TreeSet, HashSet etc), so it is not a Universal cursor. By using Enumeration & Iterator we can move only forward direction and we cannot move to the backward direction, and hence Enumeration & Iterator are single direction cursor.

  

Leave a Reply

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