The remove()
method of the CopyOnWriteArraySet
class in Java removes the element that matches the element passed as a parameter.
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.
public boolean remove(Object obj)
This method takes the element to be removed from the set
as a parameter.
The remove
method returns true
if the passed argument is present in the set
. Otherwise, it returns false
.
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);}}
In the code above,
In line 5: We create a CopyOnWriteArraySet
object named set
.
In lines 8 to 10: We add two elements (hi, hello
) to the created set
object.
In line 14: We use the remove
method of the set
object to remove the hi
element. The hi
element is present in the set
, which will be deleted, and true
is returned.
In line 18: We use the remove
method of the set
object to remove the bye
element. The bye
element is not present in the set
, so false
returns.