What is the CopyOnWriteArrayList.clear method in Java?

CopyOnWriteArrayList is a thread-safe version of an ArrayList. For all the write operations like add, it makes a fresh copy of the underlying array and performs the operation in the cloned array. Due to this, the performance is lower when compared to ArrayList. Read more about CopyOnWriteArrayList here.

The clear method can be used to delete all the elements of the CopyOnWriteArrayList object. After calling this method, the list becomes empty.

Syntax

public void clear();

This method doesn’t take any parameters and doesn’t return any value.

Code

The code below demonstrates the use of the clear method.

import java.util.concurrent.CopyOnWriteArrayList;
class Clear {
public static void main( String args[] ) {
// created a new set which can have string type elements
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
// adding 3 elements to the list
list.add("1");
list.add("2");
list.add("3");
System.out.println("The list is " + list);
// calling clear method to remove all elements of the list
list.clear();
System.out.println("After calling the clear method the list is " + list);
}
}

Explanation

In the code above,

  • In line 1: Import the CopyOnWriteArrayList class.

  • In line 5: Create a CopyOnWriteArrayList object named list.

  • In line 7-9: Use the add method of the list object to add three elements 1, 2, and 3 to the list.

  • In line 13: Use the clear method of the list object to remove all the list elements. After calling the clear method, the list becomes empty.

Free Resources