Java ListIterator add() Method Tutorial

In this section, we will learn what the ListIterator add() method is and how to use it in Java.

What is ListIterator add() Method in Java?

The Java ListIterator add() method is used to add a new element to the target collection object that the ListIterator object has a reference for.

The new element will be added before the element that would return if we called the next() method. Or it would be added after the element that would be returned if we called the previous method.

ListIterator add() Method Syntax:

void add(E e)

ListIterator add() Method Parameters

The method takes one argument and that is the element we want to add to the target collection object.

ListIterator add() Method Return Value

The return value of this method is void.

ListIterator add() Method Exception:

UnsupportedOperationException: We get this exception if the target ListIterator object does not support this method.

ClassCastException: If the argument we set for this method is not of compatible type (the same as the elements of the target collection object) we get this exception.

IllegalArgumentException: We get this exception if some aspect of the argument we set in the method doesn’t allow it to become an element of a collection object.

Example: using ListIterator add() Method in Java

import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;
public class Main {

    public static void main(String[] args){
        
        List<String> list = new ArrayList<>();
        list.add("Omid");
        list.add("Jack");
        list.add("Ellen");
        list.add("John");

        ListIterator<String> iterate = list.listIterator();

        iterate.add("The first Element");
        iterate.add("The second Element");
        for (String s : list){
         System.out.println(s);
        }
    }
}

Output:

The first Element

The second Element

Omid

Jack

Ellen

John

How Does ListIterator add() Method Work in Java?

As you can see, the two calls to the add() method caused the two elements to be added to the beginning of the target collection object.

This is because we didn’t call the next() method and so the cursor of the listIterator object was still at the beginning of this list object.

Leave a Reply