What is the CopyOnWriteArrayList.remove() method in Java?
The remove method can be used to remove an element at a specific index of the CopyOnWriteArrayList object.
CopyOnWriteArrayListis a thread-safe version of an ArrayList. For all the write operations likeadd,set, etc., it makes a fresh copy of the underlying array and performs the operations in the cloned array. Due to this, the performance is slower when compared toArrayList.
Syntax
public E remove(int index)
Parameters
This method takes the integer value representing the index of the element as an argument.
Return value
This method removes and returns the element present at the specific index.
This method throws IndexOutOfBoundsException if the index is negative or greater than the size of the list.
Code
The code below demonstrates how to use the remove method:
import java.util.concurrent.CopyOnWriteArrayList;class RemoveExample {public static void main( String args[] ) {// create CopyOnWriteArraySet object which can store integer objectCopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();// add elememtslist.add(1);list.add(2);list.add(3);// Print listSystem.out.println("The list is: " + list);// use remove method to retrieve element at index 0System.out.println("\nlist.remove(0) : " + list.remove(0));// use remove method to retrieve element at index 1System.out.println("\nlist.remove(1) : " + list.remove(1));}}
Explanation
In the code above,
-
In line 1, we import the
CopyOnWriteArrayListclass. -
In line 5, we create a
CopyOnWriteArrayListobject with the namelist. -
In lines 8-10, we use the
addmethod to add three elements to thelist. The list will be[1,2,3]. -
In line 16, we use the
removemethod with0as an argument. This will delete the element at index0and return the removed value. In our case,1is returned. Now the list will be[2,3]. -
In line 19, we use the
removemethod with1as an argument. This will delete the element at index1and return the removed value. In our case,3is returned.