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. It internally uses Set A collection that contains no duplicate elements CopyOnWriteArrayList
for 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 aboutCopyOnWriteArraySet
here.
public void clear();
This method doesn’t take any parameters and doesn’t return any value.
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);}}
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.