What is the CopyOnWriteArraySet.size method in Java?
CopyOnWriteArraySetis a thread-safe version ofthat internally uses Set A collection that contains no duplicate elements CopyOnWriteArrayListfor its operations. For all the write operations likeadd,set, etc.,CopyOnWriteArraySetmakes a fresh copy of the underlying array and operates on the cloned array. You can read more aboutCopyOnWriteArraySethere.
The size method can be used to get 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 classimport java.util.concurrent.CopyOnWriteArraySet;class Size {public static void main( String args[] ) {// Creating the CopyOnWriteSetClass ObjectCopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();// Adding the elements in the setset.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 caseSystem.out.println("The size of set is : " + set.size());}}
Explanation
In the code above, we:
-
Import the
CopyOnWriteArraySetclass. -
Create a
CopyOnWriteArraySetobject with the nameset. -
Use the
addmethod of thesetobject to add three elements ("1","2","3") toset. -
Use the
sizemethod of thesetobject to get the size ofset. In our case, our return value will be3because thesetobject has3elements.