What is the CopyOnWriteArraySet.add method in Java?
CopyOnWriteArraySetis a thread-safe version of. It internally uses the Set A collection that contains no duplicate elements. CopyOnWriteArrayListmethod for its operations. For all the write operations, like add and set, it makes a fresh copy of the underlying array and operates on the cloned array. Read more about theCopyOnWriteArraySetmethod here.
The add method of the CopyOnWriteArraySet class adds an element to the end of the CopyOnWriteArraySet object.
Syntax
public boolean add(E e);
Parameters
The add method takes the element to be added to the set as a parameter.
Return value
The add method returns true if the element is successfully added to the set.
Code
The code below demonstrates how we can use the add method:
import java.util.concurrent.CopyOnWriteArraySet;class Add {public static void main( String args[] ) {CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();set.add("hello");System.out.println("The set is " + set);set.add("hi");System.out.println("The set is " + set);}}
Code explanation
In the code given above, we:
-
Imported the
CopyOnWriteArraySetclass. -
Created a
CopyOnWriteArraySetobject with the nameset. -
Used the
addmethod of thesetobject to add an element,"hello", to the set. -
Printed the set.
-
Used the
addmethod of thesetobject to add another element,"hi", to the set. -
Printed the set again.