Replace an element in an ArrayList using the ListIterator in Java

Java 8Object Oriented ProgrammingProgramming

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>();
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>();

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);
}
Published on 18-Jan-2019 05:52:46