ListIterator Interface In Java With Examples

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated March 7, 2024

This Tutorial Explains the ListIterator Interface in Java to Traverse List Implementations. You will Learn about the Class Diagram & Methods of ListIterator Interface:

Just like Iterator, the ListIterator interface provides the functionality to traverse through the list implementations in Java and access the elements of the list.

=> Check Here To See A-Z Of Java Training Tutorials Here.

ListIterator Interface in Java

ListIterator Interface In Java

Some of the main characteristics of the ListIterator interface are listed below:

  • ListIterator was introduced in Java 1.2
  • ListIterator is a sub-interface of the Iterator interface i.e. it extends from the Iterator interface.
  • ListIterator works only with list implementations.
  • ListIterator supports all operations namely, Create, Read, Update and Delete. (Collectively called CRUD operations).
  • ListIterator is a bi-directional Iterator and it supports forward as well as backward direction iterators.
  • In the case of ListIterator, there is no current element. The cursor position is pointed to the location between the element returned by the previous () method and the element that would be returned by the next () method.

Let’s discuss more about this interface in this tutorial.

ListIterator Class Diagram

ListIterator is an interface that belongs to the Collections API framework. This interface extends from the Iterator interface. Apart from inheriting the methods of the Iterator interface, it also supports the methods for bi-directional iterations and CRUD operations.

The class diagram of ListIterator interface is shown below.

Class diagram of ListIterator interface

The above figure shows the class diagram of the ListIterator interface. In the next section, we will discuss each of the methods shown in the figure in detail.

ListIterator Methods

ListIterator interface provides the following methods as shown in the below table.

Method NamePrototypeDescription
hasNext()boolean hasNext()Checks if listIterator has more elements to traverse in forward direction.
next()E next()Returns the next element in the list. Then moves the cursor to point to the next element.
hasPrevious()boolean hasPrevious()Checks if ListIterator has more elements in the backward/reverse direction.
previous()E previous()Returns the previous element in the list and moves the cursor to one position in the backward direction.
nextIndex()int nextIndex()Returns index of the element that will be returned by call to next() method.
previousIndex()int previousIndex()Returns the index of the element that will be returned by call to previous() method.
remove()void remove()Removes the last element returned either by next() or previous() method.
set(E)void set(E e)Replaces the last element returned by either next() or previous() method with the new value.
add(E)void add(E e)Adds new element to the list.

Next, we will describe each of these methods in detail.

#1) hasNext ()

Prototype: boolean hasNext ()
Parameters: NIL
Return Value:

  • true=> list has next element
  • False=> list has no more elements

Description: This method checks if the ListIterator has more elements to traverse in the forward direction. If it has more elements then this method returns true.

#2) next ()

Prototype: E next ()
Parameters: NIL
Return Value: E=> next element in the list.
Description: The next () method returns the next element in the list and moves the cursor to the next element.
Exception Thrown: NoSuchElementException – if the ListIterator has no next element.

#3) hasPrevious ()

Prototype: boolean hasPrevious ()
Parameters: NIL
Return Value: true=> the ListIterator has previous element
Description: Checks if ListIterator has more elements in the backward/reverse direction.

#4) previous ()

Prototype: E previous ()
Parameters: NIL
Return Value: E=> previous element in the list
Description: This method returns the previous element in the list while traversing backward and then moves the cursor backward.
Exception Thrown: NoSuchElementException – if the ListIterator has no next element.

#5) nextIndex ()

Prototype: int nextIndex ()
Parameters: NIL

Return Value: int=> index of the element that will be returned by the next () method or size of the list if ListIterator is at the end of the list.

Description: This method can be called before the next () method. The nextIndex () method returns the index of the element that will be returned by the next () method. If the ListIterator is at the end of the list then this method returns the list size.

#6) previousIndex ()

Prototype: int previousIndex ()
Parameters: NIL

Return Value: int=> index of the element that will be returned by the previous () method or -1 if ListIterator is at the beginning of the list.

Description: This method can be called before the previous () method. The previousIndex () method returns the index of the element which will be returned by the previous () method. If the ListIterator is at the beginning of the list then the method returns -1.

#7) remove ()

Prototype: void remove ()
Parameters: NIL
Return Value: void

Description: The remove () method deletes the last element that was returned either by the previous() or next() method. The call to the method remove () can be made only once per call to the next() or previous() method.

Exception Thrown:

  • UnsupportedOperationException – ListIterator does not support remove operation.
  • IllegalStateException – If the current operation is in Illegal state i.e. neither next nor previous have been called yet or after the call to next or previous, then add or remove have not been called.

#8) set (E)

Prototype: void set (E e)
Parameters: e=> new element with which old element is to be replaced
Return Value: void

Description: The method set () sets the element returned by either previous () or next () method with the new value passed as an argument. This method can be called only if add() or remove() method is not called after the last call to method previous() or next().

Exception Thrown:

  • UnsupportedOperationException – ListIterator does not support the set operation.
  • ClassCastException – If the specified element cannot be added because of its class.
  • IllegalArgumentException – If the element/argument being added is illegal or invalid.
  • IllegalStateException – If the current operation is in Illegal state i.e. neither next nor previous have been called yet or after the call to next or previous, add or remove have not been called.

#9) add(E)

Prototype: void add(E e)
Parameters: e=> new element to be added to the list
Return Value: void

Description: The add () method is used to add a new element to the list. The element is added just before the element the next () would have returned, if any and after the element that the previous () method would have returned.

Note that, as a result of adding an element, there would be no change to return the value of next () but the previous() method will return just the added element.

Exception Thrown:

  • UnsupportedOperationException – ListIterator does not support the add method.
  • ClassCastException if a specified element that cannot be added because of its class.
  • IllegalArgumentException if the element/argument being added is illegal or invalid.

The following Java program shows a demonstration of all the above ListIterator methods.

import java.util.*;  
public class Main{  
public static void main(String args[]){  
        //define list and add elements to it
        List<String>nameList=new ArrayList<String>();    
        nameList.add("Savich");    
        nameList.add("Dane");    
        nameList.add("Lacey");    
        nameList.add(1,"James");    

        System.out.println("Original List:" + nameList);
        //define a list iterator for this list
        ListIterator<String> list_itr=nameList.listIterator(); 

         System.out.println("List elements in forward direction:");    
        //while there are still elements in the list, display next index and element
        while(list_itr.hasNext()){    
        System.out.println("Index:"+list_itr.nextIndex()+" Element:"+list_itr.next());
        } 
     //call set() method to set next value to "Sally"
      list_itr.set("Sally");
      System.out.println("\nList after set(\"Sally\"):" + nameList);

        //while there are elements in the list, display previous index and element
       System.out.println("\nList elements in backward direction:");    
       while(list_itr.hasPrevious()){    
       System.out.println("Index:"+list_itr.previousIndex()+" Element:"+list_itr.previous());  

        }
        //call remove () method
       list_itr.remove();
       System.out.println("List after remove():" + nameList);
}  
}  

Output:

Output of program demonstarting ListIterator methods

ListIterator Interface In Java Examples

Let us see another example of using ListIterator. In this program, we have an ArrayList of integer values. Then using ListIterator we traverse the list and display list elements.

Also, we only pick even elements in the ArrayList and change their values to odd numbers using the ListIterator methods.

import java.util.ArrayList; 
import java.util.ListIterator; 

public class Main 
{ 
    public static void main(String[] args) 
    { 
        //define ArrayList and add values to it using for loop
        ArrayList intList = new ArrayList(); 
        for (int i = 0; i < 10; i++) 
        intList.add(i+2); 

        System.out.println("Original ArrayList:" + intList); 

        // define the ListIterator 
        ListIterator list_itr = intList.listIterator(); 

        System.out.println("List elements using listIterator:");
        //while list has more elements 
        while (list_itr.hasNext()) 
        { 
            //retrieve next element 
            int i = (Integer)list_itr.next(); 

            // print the element 
           System.out.print(i + " "); 

            // change only even numbers to odd by setting value = value +1 to current element
            if (i%2==0) 
            { 
                  list_itr.set(i+1);  // set method to change value 

            } 
        } 
        System.out.println(); 
        System.out.println("Final ArrayList of odd values:" + intList); 
    } 
}

Output:

ListIterator Example - output

Frequently Asked Questions

Q #1) What is meant by iterator?

Answer: Iterator is an interface that is a part of the Collection framework in Java. This interface is present in java.util package. The iterator interface is used to iterate through the collection of objects.

Q #2) What is an iterator interface in Java?

Answer: An iterator interface in Java is used instead of Enumerations that were previously used in the Java Collection Framework. The iterator interface is present in Java since version 1.2.

Using this interface you can iterate through any Java collections and process the collection elements.

Q #3) What is the use of the listIterator () method in Java?

Answer: The listIterator () method belongs to java.util.* package. This method returns a list iterator for the particular list object that invoked it and can be used to traverse the lists and access elements. The listIterator works only on list implementations.

Q #4) Is iterator a class or an interface?

Answer: Iterator is not a class but an interface in Java. Iterator interface can be implemented by the other classes and used to iterate through list or collection elements.

Q #5) How many types of iterators are there in Java?

Answer: Iterators in Java are of three types:

  • Enumerations: This is an interface that is used to read the elements from collections like Vector, hashtable, etc. Each element is numbered according to its position in the collection.
  • Iterator: You can call this interface universal as you can apply it to any collection object to traverse through the collection. This is an improved enumeration with remove functionality along with the ability to read an element.
  • ListIterator: ListIterator is an interface that provides the bi-directional iteration i.e. in forward and backward directions. ListIterator only works with list implementations including LinkedList, ArrayList, etc.

Conclusion

ListIterator interface in Java is derived from the Iterator interface. In addition to directly inheriting the methods of the Iterator interface, the listIterator interface introduces various methods of its own that can aid the programmer in performing bidirectional iteration.

In this tutorial, we have discussed the class diagram and the various methods of ListIterator interface. We have also seen the implementation of these methods along with the ways to traverse through various lists.

=> Visit Here To See The Java Training Series For All.

Was this helpful?

Thanks for your feedback!

Leave a Comment