The set() method of CopyOnWriteArrayList in Java

Java 8Object Oriented ProgrammingProgramming

The set() method of the CopyOnWriteArrayList class is used to replace the element at the specified position in this list with the specified element. It returns the element that gets replaced.

The syntax is as follows

public E set(int index, E ele)

Here, the parameter index is the index of the element to replace and ele is the element to be stored at the specified position.

To work with CopyOnWriteArrayList class, you need to import the following package

import java.util.concurrent.CopyOnWriteArrayList;

The following is an example to implement CopyOnWriteArrayList class set() method in Java

Example

 Live Demo

import java.util.concurrent.CopyOnWriteArrayList;
public class Demo {
   public static void main(String[] args) {
      CopyOnWriteArrayList<Integer> arrList = new CopyOnWriteArrayList<Integer>();
      arrList.add(30);
      arrList.add(40);
      arrList.add(60);
      arrList.add(70);
      arrList.add(90);
      arrList.add(100);
      arrList.add(120);
      System.out.println("CopyOnWriteArrayList = " + arrList);
      System.out.println("Replaced element = " + arrList.set(3, 50 ));
      System.out.println("Updated CopyOnWriteArrayList = "+arrList);
   }
}

Output

CopyOnWriteArrayList = [30, 40, 60, 70, 90, 100, 120]
Replaced element = 70
Updated CopyOnWriteArrayList = [30, 40, 60, 50, 90, 100, 120]
raja
Published on 27-Mar-2019 08:50:38
Advertisements