What is the CopyOnWriteArraySet.remove(Object) method in Java?
Definition
The remove() method of the CopyOnWriteArraySet class in Java removes the element that matches the element passed as a parameter.
The CopyOnWriteArraySet class
The CopyOnWriteArraySet is a thread-safe version of CopyOnWriteArrayList for its operations. For all the write operations like add, set, etc., the class makes a fresh copy of the underlying array and operates on the cloned array.
Syntax
public boolean remove(Object obj)
Parameters
This method takes the element to be removed from the set as a parameter.
Return value
The remove method returns true if the passed argument is present in the set. Otherwise, it returns false.
Code
The code below demonstrates the use of the remove method:
import java.util.concurrent.CopyOnWriteArrayList;class Remove {public static void main( String args[] ) {// Creating CopyOnWriteArrayList which can contain string elementsCopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();// add elememtslist.add("hi");list.add("hello");System.out.println("The list is: " + list);// remove element - hiSystem.out.println("\nCalling list.remove('hi'). Is Removed :" + list.remove("hi"));System.out.println("After removing element 'hi'. The list is: " + list);// remove element - byeSystem.out.println("\nCalling list.remove('bye'). Is Removed :" + list.remove("bye"));System.out.println("The list is: " + list);}}
Explanation
In the code above,
-
In line 5: We create a
CopyOnWriteArraySetobject namedset. -
In lines 8 to 10: We add two elements (
hi, hello) to the createdsetobject. -
In line 14: We use the
removemethod of thesetobject to remove thehielement. Thehielement is present in theset, which will be deleted, andtrueis returned. -
In line 18: We use the
removemethod of thesetobject to remove thebyeelement. Thebyeelement is not present in theset, sofalsereturns.