ListIterator Example Methods


We have seen earlier iterating Vector elements with Enumeration and Iterator. Now let us see with ListIterator. ListIterator is derived from Iterator interface and comes with more methods than Iterator. Always, subclass is richer than super class.

Following is the class signature

public interface ListIterator extends Iterator

We know between two interfaces extends should be used (not implements).

Following are the methods of ListIterator interface.

  1. public abstract boolean hasNext(); // inherited from Iterator
  2. public abstract void remove(); // inherited from Iterator
  3. public abstract Object next(); // inherited from Iterator
  4. public abstract boolean hasPrevious(); // does not exist with Iterator
  5. public abstract Object previous(); // does not exist with Iterator
  6. public abstract int nextIndex(); // does not exist with Iterator
  7. public abstract int previousIndex(); // does not exist with Iterator
  8. public abstract void set(jObject); // does not exist with Iterator
  9. public abstract void add(Object); // does not exist with Iterator

The last 6 methods which do not exist in Iterator add more functionality to ListIterator.

  1. boolean hasPrevious(): The elements can be iterated back and printed in reverse order.
  2. Object previous(): It is exactly opposite to next(). next() moves the cursor forward but previous() moves backward.
  3. void set(Object): Replaces the original element with a new element.
  4. void add(Object): Adds a new element to the data structure.

Like the remove() method (inherited from Iterator), the add() and set() methods also affect the original data structure itself.

Let us do with the methods through the same Vector example.

import java.util.*;
public class ListIteratorDemo
{
  public static void main(String args[])
  {
    Vector vect1 = new Vector();
    vect1.addElement("Raju");  
    vect1.addElement("Reddy");
    vect1.addElement("Rao");
    vect1.addElement("Ratnakar");

    ListIterator it1 = vect1.listIterator();

    System.out.print("Elements with next() method: ");		
    while(it1.hasNext())
    {
      Object obj1 = it1.next();
      System.out.print(obj1 + " ");
    }
                     // let us take the cursor backwards
    System.out.print("\nElements with previous() method: ");	
    while(it1.hasPrevious())
    {
      Object obj2 = it1.previous();
      System.out.print(obj2 + " ");
    }
                                          // affecting the elements  
    while(it1.hasNext())
    {
      Object obj1 = it1.next();

      if(obj1.equals("Raju"))
            it1.remove();                 // Raju is removed

      if(obj1.equals("Reddy"))            // Reddy replaced by Yadav
            it1.set("Yadav");  
    }
    it1.add("Jyothi");                    // new elements are added
    it1.add("Jyostna");
                     // now let us print the elements after affecting
    ListIterator it2 = vect1.listIterator();
    System.out.print("\nElements after operations: ");
    while(it2.hasNext())
    {
      Object obj2 = it2.next();
      System.out.print(obj2 + " ");
   }
 }
}

ListIterator Example Methods

       if(obj1.equals("Raju"))
            it1.remove();                     

When the next() element returns Raju, the element is removed.

        
        if(obj1.equals("Reddy"))   // Reddy replaced by Yadav
            it1.set("Yadav");  

When the next() element returns Reddy, the element is replaced by Yadav.

       it1.add("Jyothi");                
       it1.add("Jyostna");

Two elements are added which did not exist earlier.

Observe the screenshot. First all the elements are printed with forward direction with hasNext() and next() methods as in the case of Iterator. With hasPrevious() and previous() methods the elements are printed in the reverse order. Two new operations in ListIterator (that do not exist in Iterator) are set() and add(). remove() method exist in both.

Precautions while using Iterator and ListIterator

1. Dependency Operations

remove() and set() operations are dependency operations and depend on next() method. Calling remove() and set() methods without calling next() method is an error.

         it1.next();
         it1.remove();       

The above code works fine. But calling it1.remove() without calling it1.next() is an exception. The following code throws IllegalStateException.

         while(it1.hasNext())
         {
            // Object obj1 = it1.next();
           it1.remove();
         }

2. Fail-fast (ConcurrentModificationException)

While iteration is going with iterators, modifications with the collections object cannot be done like additions or deletions etc. The Iterator and ListIterator objects returned by the collection classes are fail-fast.

Leave a Comment

Your email address will not be published.