ArrayList listIterator() method example

ArrayList listIterator() returns a list iterator over the elements in this list. It is a bi-directional iterator which is fail-fast in nature.

By default, elements returned by the list iterator are in proper sequence.

1. ArrayList listIterator() method

The listIterator() method is overloaded and comes in two variants:

  • ListIterator listIterator() – Returns a list iterator over the elements in this list.
  • ListIterator listIterator(int index) – Returns 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 index minus one.

Method parameter – index of the first element to be returned from the list iterator.
Method returns – a list iterator over the elements.
Method throwsIndexOutOfBoundsException – if the index is out of range (less than 0 or greater than list size).

2. ArrayList listIterator() – Iteration

Java program to iterate an arraylist using list iterator obtained through listIterator() method. We will learn to iterate the list in forward and backward direction.

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

public class ArrayListExample 
{
    public static void main(String[] args) throws CloneNotSupportedException 
    {
        ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
        
        ListIterator<String> listItr = alphabets.listIterator();
        
        System.out.println("===========Forward=========");
        
        while(listItr.hasNext()) {
            System.out.println(listItr.next());
        }
        
        System.out.println("===========Backward=========");
        
        while(listItr.hasPrevious()) {
            System.out.println(listItr.previous());
        }
    }
}

Program output.

===========Forward=========
A
B
C
D
===========Backward=========
D
C
B
A

3. ArrayList listIterator() – Add/Remove

ListIterator supports to add and remove elements in the list while we are iterating over it.

  • listIterator.add(Element e) – The element is inserted immediately before the element that would be returned by next() or after the element that would be returned previous() method.
  • listIterator.remove() – Removes from the list the last element that was returned by next() or previous() method.
  • import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.ListIterator;
    
    public class ArrayListExample 
    {
        public static void main(String[] args) throws CloneNotSupportedException 
        {
            ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
            
            ListIterator<String> listItr = alphabets.listIterator();
            
            System.out.println(listItr.next());		//A
            System.out.println(listItr.next());		//B
            
            listItr.add("E");       
            
            System.out.println(alphabets); //["A", "B", "E", "C", "D"]
            
            System.out.println(listItr.previous());	//E
            System.out.println(listItr.next());		//E
            
            System.out.println(listItr.next());		//C
            
            listItr.remove();       
            
            System.out.println(alphabets); //["A", "B", "E", "D"]
            
            System.out.println(listItr.next());		//D
        }
    }
    

    Program output.

    A
    B
    [A, B, E, C, D]
    E
    E
    C
    D
    [A, B, E, D]
    

    4. ArrayList listIterator() – Fail fast

    ListIterator is fail fast. It means if we modibt the arraylist after list iterator is created, then it will throw ConcurrentModificationException on next() or previous() method call.

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.ListIterator;
    
    public class ArrayListExample 
    {
        public static void main(String[] args) throws CloneNotSupportedException 
        {
            ArrayList<String> alphabets = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
            
            ListIterator<String> listItr = alphabets.listIterator();
            
            System.out.println(listItr.next());     //A
            System.out.println(listItr.next());     //B
                
            alphabets.add("E");       
            
            System.out.println(alphabets);          //["A", "B", "C", "D", "E"]
            
            System.out.println(listItr.next());     //Error
        }
    }
    

    Program output.

    A
    B
    [A, B, C, D, E]
    Exception in thread "main" java.util.ConcurrentModificationException
    	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    	at java.util.ArrayList$Itr.next(ArrayList.java:851)
    	at com.howtodoinjava.example.ArrayListExample.main(ArrayListExample.java:22)
    

    5. Differences between Iterator and ListIterator

    Iterator ListIterator
    Can be used to iterate all collection classes. Can be used to iterate only List implemented classes.
    Supports only forward direction only iteration. Supports both forward and backward direction iterations.
    Supports only READ and DELETE operations. Supports all CRUD operations.
    Obtained through iterator() method. Obtained through listIterator() method.

    That’s all for the ArrayList listIterator() method in Java.

    Happy Learning !!

    Read More:

    A Guide to Java ArrayList
    ArrayList Java Docs
    ListIterator Java Docs

    Leave a Reply

    1 Comment
    Most Voted
    Newest Oldest
    Inline Feedbacks
    View all comments

    About Us

    HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

    It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

    Our Blogs

    REST API Tutorial