The set(E e) method in the class CopyOnWriteArrayList class replaces the element at the specified index with the element provided as a parameter to the method. The method returns the element that has been replaced by the new element.
Syntax:
public E set(int index, E element)
Parameters: The method takes two parameters mentioned below:
- Index: Contains the position at which the new element is to replace the existing one. It is mandatory to add.
- Element: Contains the new element to be replaced with.
Return Value: The method returns the element that has been replaced.
Exceptions: The method throws IndexOutOfBoundsException occurs when the method has an index that is either less than 0 or greater than the size of the list.
Below are some programs to illustrate the use of CopyOnWriteArrayList.set() method:
Program 1:
Java
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListDemo {
public static void main(String[] args)
{
CopyOnWriteArrayList<String> arrayList
= new CopyOnWriteArrayList<String>();
arrayList.add( 0 , "geeks" );
arrayList.add( 1 , "for" );
arrayList.add( 2 , "geeksforgeeks" );
System.out.println( "CopyOnWriteArrayList: "
+ arrayList);
String returnValue
= arrayList.set( 0 , "toodles" );
System.out.println( "The value returned "
+ "on calling set() method:"
+ returnValue);
System.out.println( "CopyOnWriteArrayList "
+ "after calling set():"
+ arrayList);
}
}
|

Program 2:
Java
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListDemo {
public static void main(String[] args)
{
CopyOnWriteArrayList<String> arrayList
= new CopyOnWriteArrayList<String>();
arrayList.add( 0 , "geeks" );
arrayList.add( 1 , "for" );
arrayList.add( 2 , "geeksforgeeks" );
System.out.println( "CopyOnWriteArrayList: "
+ arrayList);
try {
System.out.println( "Trying to add "
+ "element at index 4 "
+ "using set() method" );
String returnValue
= arrayList.set( 4 , "toodles" );
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
