Replace Element in ArrayList Using ListIterator in Java



An element in ArrayList can be replaced using the ListIterator method set(). This method has a single parameter i.e. the element that is to be replaced and the set() method replaces it with the last element returned by the next() or previous() methods.

A program that demonstrates this is given as follows.

Example

 Live Demo

import java.util.ArrayList;
import java.util.ListIterator;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String> aList = new ArrayList<String>();
      aList.add("Amanda");
      aList.add("Taylor");
      aList.add("Justin");
      aList.add("Emma");
      aList.add("Peter");
      System.out.println("The ArrayList elements are: ");
      for (String s : aList) {
         System.out.println(s);
      }
      ListIterator<String> li = aList.listIterator();
      li.next();
      li.set("Monica");
      System.out.println("\nThe ArrayList elements are: ");
      for (String s : aList) {
         System.out.println(s);
      }
   }
}

Output

The output of the above program is as follows

The ArrayList elements are:
Amanda
Taylor
Justin
Emma
Peter

The ArrayList elements are:
Monica
Taylor
Justin
Emma
Peter

Now let us understand the above program.

The ArrayList is created and ArrayList.add() is used to add the elements to the ArrayList. Then the ArrayList elements are displayed. A code snippet which demonstrates this is as follows

ArrayList<String> aList = new ArrayList<String>();
aList.add("Amanda");
aList.add("Taylor");
aList.add("Justin");
aList.add("Emma");
aList.add("Peter");

System.out.println("The ArrayList elements are: ");  
for (String s : aList) {
   System.out.println(s);
}

The element “Amanda” is replaced by “Monica” using the ListIterator method set(). Then the ArrayList elements are again displayed. A code snippet which demonstrates this is as follows −

ListIterator<String> li = aList.listIterator();
   
li.next();
li.set("Monica");
   
System.out.println("\nThe ArrayList elements are: ");  
for (String s : aList) {
   System.out.println(s);
}
Updated on: 2020-06-29T13:47:32+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements