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 elementsCopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();// adding 3 elements to the listlist.add("1");list.add("2");list.add("3");System.out.println("The list is " + list);// calling clear method to remove all elements of the listlist.clear();System.out.println("After calling the clear method the list is " + list);}}
Explanation
In the code above,
-
In line 1: Import the
CopyOnWriteArrayListclass. -
In line 5: Create a
CopyOnWriteArrayListobject namedlist. -
In line 7-9: Use the
addmethod of thelistobject to add three elements1,2, and3to the list. -
In line 13: Use the
clearmethod of thelistobject to remove all the list elements. After calling theclearmethod, the list becomes empty.