HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Collections Framework / Java ArrayList / ArrayList listIterator() method example

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 throws – IndexOutOfBoundsException – 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

    IteratorListIterator
    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

    Was this post helpful?

    Let us know if you liked the post. That’s the only way we can improve.

    Share this:

    • Twitter
    • Facebook
    • LinkedIn
    • Reddit

    About Lokesh Gupta

    A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

    Feedback, Discussion and Comments

    1. Ajit Kumar

      December 21, 2018

      using example 3 i cleared all the doubts about iterator and listiterator whatever i had earlier hats off nice tutorial

    Comments are closed on this article!

    Search Tutorials

    ArrayList Methods

    • ArrayList – Introduction
    • ArrayList – add()
    • ArrayList – addAll()
    • ArrayList – clear()
    • ArrayList – clone()
    • ArrayList – contains()
    • ArrayList – ensureCapacity()
    • ArrayList – forEach()
    • ArrayList – get()
    • Arraylist – indexOf()
    • Arraylist – lastIndexOf()
    • ArrayList – listIterator()
    • ArrayList – remove()
    • ArrayList – removeAll()
    • ArrayList – removeIf()
    • ArrayList – retainAll()
    • ArrayList – sort()
    • ArrayList – spliterator()
    • ArrayList – subList()
    • ArrayList – toArray()

    ArrayList Examples

    • ArrayList – Initialize arraylist
    • ArrayList – Iteration
    • ArrayList – Add/replace element
    • ArrayList – Add multiple elements
    • ArrayList – Check empty list
    • ArrayList – Remove element
    • ArrayList – Replace element
    • ArrayList – Empty arraylist
    • ArrayList – Synchronized arraylist
    • ArrayList – Compare two lists
    • ArrayList – Remove duplicates
    • ArrayList – Merge two lists
    • ArrayList – Serialization
    • ArrayList – Swap two elements
    • Convert ArrayList to Array
    • Convert Array to ArrayList
    • Convert HashSet to ArrayList
    • Convert LinkedList to ArrayList
    • Convert Vector to ArrayList
    • ArrayList vs LinkedList
    • ArrayList vs Vector

    Java Tutorial

    • Java Introduction
    • Java Keywords
    • Java Flow Control
    • Java OOP
    • Java Inner Class
    • Java String
    • Java Enum
    • Java Collections
    • Java ArrayList
    • Java HashMap
    • Java Array
    • Java Sort
    • Java Clone
    • Java Date Time
    • Java Concurrency
    • Java Generics
    • Java Serialization
    • Java Input Output
    • Java New I/O
    • Java Exceptions
    • Java Annotations
    • Java Reflection
    • Java Garbage collection
    • Java JDBC
    • Java Security
    • Java Regex
    • Java Servlets
    • Java XML
    • Java Puzzles
    • Java Examples
    • Java Libraries
    • Java Resources
    • Java 14
    • Java 12
    • Java 11
    • Java 10
    • Java 9
    • Java 8
    • Java 7

    Meta Links

    • About Me
    • Contact Us
    • Privacy policy
    • Advertise
    • Guest and Sponsored Posts

    Recommended Reading

    • 10 Life Lessons
    • Secure Hash Algorithms
    • How Web Servers work?
    • How Java I/O Works Internally?
    • Best Way to Learn Java
    • Java Best Practices Guide
    • Microservices Tutorial
    • REST API Tutorial
    • How to Start New Blog

    Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

    • Java 15 New Features
    • Sealed Classes and Interfaces
    • EdDSA (Ed25519 / Ed448)