What is the CopyOnWriteArraySet.add method in Java?

CopyOnWriteArraySet is a thread-safe version of SetA collection that contains no duplicate elements.. It internally uses the CopyOnWriteArrayList method 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 the CopyOnWriteArraySet method 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 CopyOnWriteArraySet class.

  • Created a CopyOnWriteArraySet object with the name set.

  • Used the add method of the set object to add an element, "hello", to the set.

  • Printed the set.

  • Used the add method of the set object to add another element, "hi", to the set.

  • Printed the set again.

Free Resources