CopyOnWriteArraySet
is a thread-safe version ofthat internally uses Set A collection that contains no duplicate elements CopyOnWriteArrayList
for its operations. For all the write operations likeadd
,set
, etc.,CopyOnWriteArraySet
makes a fresh copy of the underlying array and operates on the cloned array. You can read more aboutCopyOnWriteArraySet
here.
The size
method can be used to get the CopyOnWriteArraySet
object.
public int size()
This method doesn’t take any arguments.
size
returns the number of elements present in the set
as an integer.
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());}}
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.