Java ListIterator set() Method Tutorial

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

What is ListIterator set() Method in Java?

The Java ListIterator set() method is used to replace the current element that was returned from either the next() or previous() method with a new element.

Note: We can only call the set() method if we didn’t call the remove() or add() method directly after calling to either next() or previous() method. Otherwise, we will get an exception in return.

ListIterator set() Method Syntax:

void set(E e)

ListIterator set() Method Parameters

The method takes only one argument, and that is the element we want to replace with the element that was returned from the target collection object as a result of calling either the next() or previous() method.

ListIterator set() Method Return Value

The return value of the method is void.

ListIterator set() Method Exception:

The method might throw 4 types of exceptions:

  • UnsupportedOperationException: we get this exception if this method is not supported with the target ListIterator object.
  • ClassCastException: We get this exception if we attempt to set a value as the argument of the method that is of incompatible type.
  • IllegalArgumentException: We get this exception if the value we set as the argument of the method has a property that prevent it from becoming an element of a collection.
  • IllegalStateException: If neither the next() or previous() method has been called or the add() or remove() method was called before calling the set() method, we will get this exception.

Example: using ListIterator set() 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();
        int i = 0;
        while(iterate.hasNext()){
         String value = iterate.next();
         iterate.set(i+"- "+ value);
         i++;
        }
         for (String s: list){
            System.out.println(s);
         }
    }
}

Output:

0- Omid

1- Jack

2- Ellen

3- John
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies