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.

CopyOnWriteArrayList is a thread-safe version of an ArrayList. For all the write operations like add, 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 to ArrayList.

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 object
CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();
// add elememts
list.add(1);
list.add(2);
list.add(3);
// Print list
System.out.println("The list is: " + list);
// use remove method to retrieve element at index 0
System.out.println("\nlist.remove(0) : " + list.remove(0));
// use remove method to retrieve element at index 1
System.out.println("\nlist.remove(1) : " + list.remove(1));
}
}

Explanation

In the code above,

  • In line 1, we import the CopyOnWriteArrayList class.

  • In line 5, we create a CopyOnWriteArrayList object with the name list.

  • In lines 8-10, we use the add method to add three elements to the list. The list will be [1,2,3].

  • In line 16, we use the remove method with 0 as an argument. This will delete the element at index 0 and return the removed value. In our case,1 is returned. Now the list will be [2,3].

  • In line 19, we use the remove method with 1 as an argument. This will delete the element at index 1 and return the removed value. In our case,3 is returned.

Free Resources