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 SetA collection that contains no duplicate elements. It internally uses 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 elements
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
// add elememts
list.add("hi");
list.add("hello");
System.out.println("The list is: " + list);
// remove element - hi
System.out.println("\nCalling list.remove('hi'). Is Removed :" + list.remove("hi"));
System.out.println("After removing element 'hi'. The list is: " + list);
// remove element - bye
System.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 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.