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.
CopyOnWriteArraySetis a thread-safe version of. It internally uses Set A collection that contains no duplicate elements CopyOnWriteArrayListfor its operations. For all the write operations likeadd,set, etc, it makes a fresh copy of the underlying array and operates on the cloned array. Read more aboutCopyOnWriteArraySethere.
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 elementsCopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();// add three elements to the setset.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 setset.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
CopyOnWriteArraySetclass. -
In line 5: Created a
CopyOnWriteArraySetobject namedset. -
In line 7-9: Used the
add()method of theset()object to add three elements("1","2","3") toset. -
In line 12: Used the
clear()method of thesetobject to remove all the elements. After calling theclear()method,setbecomes empty.