What is the CopyOnWriteArraySet.clear method in Java?

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

CopyOnWriteArraySet is a thread-safe version of SetA collection that contains no duplicate elements. It internally uses CopyOnWriteArrayList for its operations. For all the write operations like add, set, etc, it makes a fresh copy of the underlying array and operates on the cloned array. Read more about CopyOnWriteArraySet here.

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.CopyOnWriteArraySet;
class Clear {
public static void main( String args[] ) {
//create a new set which can hold string type elements
CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();
// add three elements to the set
set.add("1");
set.add("2");
set.add("3");
System.out.println("The set is " + set);
// call clear method to remove all the elements of the set
set.clear();
System.out.println("After calling the clear method the set is " + set);
}
}

Explanation

In the code above, we have :

  • In line 1: Imported the CopyOnWriteArraySet class.

  • In line 5: Created a CopyOnWriteArraySet object named set.

  • In line 7-9: Used the add() method of the set() object to add three elements("1","2","3") to set.

  • In line 12: Used the clear() method of the set object to remove all the elements. After calling the clear() method, set becomes empty.

Free Resources