What is the CopyOnWriteArraySet.size method in Java?

CopyOnWriteArraySet is a thread-safe version of SetA collection that contains no duplicate elements that internally uses CopyOnWriteArrayList for its operations. For all the write operations like add, set, etc., CopyOnWriteArraySet makes a fresh copy of the underlying array and operates on the cloned array. You can read more about CopyOnWriteArraySet here.

The size method can be used to get the sizeNumber of elements present in the set of the CopyOnWriteArraySet object.

Syntax

public int size()

Parameters

This method doesn’t take any arguments.

Return value

size returns the number of elements present in the set as an integer.

Code

The code below demonstrates how to use the size method.

// Importing the CopyOnWriteArraySet class
import java.util.concurrent.CopyOnWriteArraySet;
class Size {
public static void main( String args[] ) {
// Creating the CopyOnWriteSetClass Object
CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();
// Adding the elements in the set
set.add("1");
set.add("2");
set.add("3");
System.out.println("The set is " + set);
// Using the size function to output the number of elements in the set
// which is 3 in this case
System.out.println("The size of set is : " + set.size());
}
}

Explanation

In the code above, we:

  • Import the CopyOnWriteArraySet class.

  • Create a CopyOnWriteArraySet object with the name set.

  • Use the add method of the set object to add three elements ("1","2","3") to set.

  • Use the size method of the set object to get the size of set. In our case, our return value will be 3 because the set object has 3 elements.

Free Resources