The Wayback Machine - https://web.archive.org/web/20250305174150/https://www.geeksforgeeks.org/listiterator-in-java/
Open In App

ListIterator in Java

Last Updated : 01 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

ListIterator is one of the four java cursors. It is a java iterator that is used to traverse all types of lists including ArrayList, Vector, LinkedList, Stack, etc. It is available since Java 1.2. It extends the iterator interface.

The hierarchy of ListIterator is as follows: 

ListIterator Hierarchy in Java

Some Important points about ListIterator

  1. It is useful for list implemented classes.
  2. Available since java 1.2.
  3. It supports bi-directional traversal. i.e both forward and backward directions.
  4. It supports all the four CRUD operations(Create, Read, Update, Delete) operations.

Interesting Fact about ListIterator

There is no current element in ListIterator. Its cursor always lies between the previous and next elements. The previous() will return to the previous elements and the next() will return to the next element. Therefore, for a list of n length, there are n+1 possible cursors.

lisiterator cursors

Syntax: Declaration

public interface ListIterator<E> extends Iterator<E>

Where E represents the generic type i.e any parameter of any type/user-defined object.

Syntax: To get a list Iterator on a list

ListIterator<E> listIterator()  

This returns the list iterator of all the elements of the list.

Example:

Java




// Java Program to Show the Usage of listIterator
 
import java.util.*;
 
public class ListIteratorDemo {
   
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a list of names
        List<String> names = new LinkedList<>();
       
        names.add("Welcome");
        names.add("To");
        names.add("Gfg");
 
        // Getting ListIterator
        ListIterator<String> namesIterator
            = names.listIterator();
 
        // Traversing elements using next() method
        while (namesIterator.hasNext()) {
            System.out.println(namesIterator.next());
        }
 
        // for-each loop creates Internal Iterator here.
        for (String s : names) {
            System.out.println(s);
        }
    }
}


Output

Welcome
To
Gfg
Welcome
To
Gfg

ListIterator is a bi-directional iterator. For this functionality, it has two kinds of methods:

1. Forward direction iteration

  • hasNext(): This method returns true when the list has more elements to traverse while traversing in the forward direction
  • next(): This method returns the next element of the list and advances the position of the cursor.
  • nextIndex(): This method returns the index of the element that would be returned on calling the next() method.

2. Backward direction iteration

  • hasPrevious(): This method returns true when the list has more elements to traverse while traversing in the reverse direction
  • previous(): This method returns the previous element of the list and shifts the cursor one position backward.
  • previousIndex(): This method returns the index of the element that would be returned on calling the previous() method.

Example code showing both forward and backward direction iterations using list Iterator:

Java




// Java Program to traverse the list both in forward and
// backward direction using listIterator
 
import java.util.*;
 
public class GFG {
   
    public static void main(String[] args)
    {
          // list of names
        List<String> names = new LinkedList<>();
        names.add("learn");
        names.add("from");
        names.add("Geeksforgeeks");
 
        // Getting ListIterator
        ListIterator<String> listIterator
            = names.listIterator();
 
        // Traversing elements
        System.out.println("Forward Direction Iteration:");
        while (listIterator.hasNext()) {
            System.out.println(listIterator.next());
        }
 
        // Traversing elements, the iterator is at the end
        // at this point
        System.out.println("Backward Direction Iteration:");
        while (listIterator.hasPrevious()) {
            System.out.println(listIterator.previous());
        }
    }
}


Output

Forward Direction Iteration:
learn
from
Geeksforgeeks
Backward Direction Iteration:
Geeksforgeeks
from
learn

ArrayList Iterator Methods

A. listIterator(): The listIterator() method of java.util.ArrayList class is used to return a list iterator over the elements in this list (in proper sequence). The returned list iterator is fail-fast.

Syntax:

public ListIterator listIterator()

Return Value: This method returns a list iterator over the elements in this list (in proper sequence).

B. listIterator(int index)

This listIterator(int index) method is used to return a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. The specified index indicates the first element that would be returned by an initial call to next. An initial call to the previous would return the element with the specified index minus one. The returned list iterator is fail-fast.

Syntax:

public ListIterator listIterator(int index)

Parameters: This method takes the index of the first element as a parameter to be returned from the list iterator (by a call to next)

Return Value: This method returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.

Exception: This method throws IndexOutOfBoundsException if the index is out of range (index size()).

Advantages:

  • It supports all four CRUD (Create, Read, Update, Delete) operations.
  • It supports Bi-directional traversing i.e both forward and backward direction iteration.
  • Simple method names are easy to use.

Limitations:

  • This iterator is only for list implementation classes.
  • Not a universal cursor.
  • It is not applicable to all collection API.
  • Parallel iteration of elements is not supported by the list Iterator.
  • listiterator does not support the good performance of numerous elements iteration.

Iterator v/s ListIterator

Similarities:

  • They both are introduced in java 1.2.
  • They both are used for iteration lists.
  • They both support forward direction traversal.
  • They both supports READ and DELETE operations.

Differences:

                Iterator

                                           ListIterator

It can traverse a collection of any type.  It traverses only list collection implemented classes like LinkedList, ArrayList, etc.
Traversal can only be done in forwarding direction. Traversal of elements can be done in both forward and backward direction.
Iterator object can be created by calling iterator() method of the collection interface. ListIterator object can be created by calling directions listIterator() method of the collection interface.
Deletion of elements is not allowed. Deletion of elements is allowed.
It throws ConcurrentModificationException on doing addition operation. Hence, addition is not allowed.  Addition of elements is allowed.
In iterator, we can’t access the index of the traversed element. In listIterator, we have nextIndex() and previousIndex() methods for accessing the indexes of the traversed or the next traversing element.
Modification of any element is not allowed. Modification is allowed.

Methods of ListIterator

Method

Description

add(E e) This method inserts the specified element into the list.
hasNext(), This returns true if the list has more elements to traverse.
hasPrevious() This returns true if the list iterator has more elements while traversing the list in the backward direction.
next() This method returns the next element and increases the cursor by one position.
nextIndex() This method returns the index of the element which would be returned on calling the next() method.
previous() This method returns the previous element of the list and shifts the cursor one position backward
previousIndex() This method returns the index of the element which would be returned on calling the previous() method.
remove() This method removes the last element from the list that was returned on calling next() or previous() method element from.
set(E e) This method replaces the last element that was returned on calling next() or previous() method with the specified element.

Methods declared in interface java. util.Iterator

Method

Description

default void forEachRemaining​(Consumer<? super E> action) Performs the given action for each remaining element until all elements have been processed or the action throws an exception.

Kickstart your Java journey with our online course on Java Programming, covering everything from basics to advanced concepts. Complete real-world coding challenges and gain hands-on experience. Join the Three 90 Challenge—finish 90% in 90 days for a 90% refund. Start mastering Java today!


Next Article
Article Tags :
Practice Tags :

Similar Reads

LinkedList listIterator() Method in Java
In Java, the listIterator() method of the LinkedList class returns a ListIterator that allows us to iterate over the elements of the list.Example: Java// Java Program to Demonstrate the // use of listIterator() in LinkedList import java.util.LinkedList; import java.util.ListIterator; public class Geeks { public static void main(String args[]) { //
3 min read
Java AbstractSequentialList | ListIterator()
AbstractSequentialList listIterator(): method in Java is used to get a listIterator over this list. It returns a list iterator over the elements in this list (in proper sequence). Syntax: public abstract ListIterator listIterator(int index) Parameters: This method takes a parameter index which is the index of first element to be returned from the l
2 min read
CopyOnWriteArrayList listIterator() method in Java
The listIterator() method of CopyOnWriteArrayList returns an listIterator over the elements in this list in proper sequence. The listIterator does NOT support the remove, set or add methods. Syntax: public ListIterator listIterator() Parameters: The function does not accept any parameters. Return Value: The function returns a list iterator over th
3 min read
Stack listIterator() method in Java with Example
The listIterator() method of Java.util.Stack class is used to return a list iterator over the elements in this stack (in proper sequence). The returned list iterator is fail-fast. Syntax: public ListIterator listIterator() Return Value: This method returns a list iterator over the elements in this stack (in proper sequence). Below are the examples
2 min read
Stack listIterator(int) method in Java with Example
The listIterator(int) method of Stack Class is used to return a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. The specified index indicates the first element that would be returned by an initial call to next. An initial call to previous would return the element with the specified
2 min read
Difference between an Iterator and ListIterator in Java
Iterators are used in Collection framework in Java to retrieve elements one by one. It can be applied to any Collection object. By using Iterator, we can perform both read and remove operations. Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque and also in al
3 min read
Retrieving Elements from Collection in Java (For-each, Iterator, ListIterator & EnumerationIterator)
Prerequisite: Collection in Java Following are the 4 ways to retrieve any elements from a collection object: For-each For each loop is meant for traversing items in a collection. // Iterating over collection 'c' using for-each for (Element e: c) System.out.println(e); We read the ‘:’ used in for-each loop as “in”. So loop reads as “for each eleme
3 min read
Reverse an ArrayList in Java using ListIterator
Assuming you have gone through arraylist in java and know about arraylist. This post contains different examples for reversing an arraylist which are given below:1. By writing our own function(Using additional space): reverseArrayList() method in RevArrayList class contains logic for reversing an arraylist with integer objects. This method takes an
6 min read
AbstractList listIterator() Method in Java with Examples
The listIterator() method of java.util.AbstractList class is used to return a list-iterator containing the same elements as that of the AbstractList in proper and same sequence starting from a specific position or index number which is passed as a parameter to this method. Syntax: ListIterator new_list = AbstractList.listIterator(int index); Parame
2 min read
Vector listIterator() method in Java with Examples
java.util.Vector.listIterator() This method returns a list iterator over the elements of a Vector object in proper sequence. It is bidirectional, so both forward and backward traversal is possible, using next() and previous() respectively. The iterator thus returned is fail-fast. This means that structurally modifying the vector after the iterator
3 min read