HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions

ArrayList listIterator() method example

By Lokesh Gupta | Filed Under: Java ArrayList

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

    About Lokesh Gupta

    Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

    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

      Reply

    Ask Questions & Share Feedback Cancel reply

    Your email address will not be published. Required fields are marked *

    *Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
    [java] 
    public static void main (String[] args) {
    ...
    }
    [/java]

    Search Tutorials

    • Email
    • Facebook
    • RSS
    • Twitter

    ArrayList Methods

    • 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 Collections

    • Collections Framework
    • Array
    • ArrayList
    • LinkedList
    • HashMap
    • Hashtable
    • LinkedHashMap
    • TreeMap
    • HashSet
    • LinkedHashSet
    • TreeSet
    • Comparable
    • Comparator
    • Iterator
    • ListIterator
    • Spliterator
    • PriorityQueue
    • PriorityBlockingQueue
    • ArrayBlockingQueue
    • LinkedTransferQueue
    • CopyOnWriteArrayList
    • CopyOnWriteArraySet
    • Collection Sorting
    • Interview Questions

    Popular Tutorials

    • Java 8 Tutorial
    • Core Java Tutorial
    • Java Collections
    • Java Concurrency
    • Spring Boot Tutorial
    • Spring AOP Tutorial
    • Spring MVC Tutorial
    • Spring Security Tutorial
    • Hibernate Tutorial
    • Jersey Tutorial
    • Maven Tutorial
    • Log4j Tutorial
    • Regex Tutorial

    Meta Links

    • Advertise
    • Contact Us
    • Privacy policy
    • About Me

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