The add(E e) method of CopyOnWriteArraySet inserts the element passed in the parameter to the end of the Set or at a specified index in the Set. The function returns true on addition of new element to the Set.
Syntax:
public boolean add(E e)
Parameters: The function accepts a single mandatory parameter element which specifies the element to be added in the Set.
Return Value: The function returns true on addition in the Set.
Below programs illustrate the above function:
Program 1:
// Java Program to illustrate the CopyOnWriteArraySet // add(element) method in Java import java.util.concurrent.CopyOnWriteArraySet; import java.util.*; public class GFG { public static void main(String[] args) { // create object of CopyOnWriteArraySet CopyOnWriteArraySet<Integer> ArrSet = new CopyOnWriteArraySet<Integer>(); // Add elements ArrSet.add( 2 ); ArrSet.add( 3 ); ArrSet.add( 4 ); ArrSet.add( 7 ); // print CopyOnWriteArraySet System.out.println( "CopyOnWriteArraySet: " + ArrSet); // 4 is already present hence cannot add System.out.println( "On adding 4 it returns " + ArrSet.add( 4 )); // print CopyOnWriteArraySet System.out.println( "Updated CopyOnWriteArraySet: " + ArrSet); } } |
CopyOnWriteArraySet: [2, 3, 4, 7] On adding 4 it returns false Updated CopyOnWriteArraySet: [2, 3, 4, 7]
Program 2:
// Java Program to illustrate the CopyOnWriteArraySet // add(element) method in Java import java.util.concurrent.CopyOnWriteArraySet; import java.util.*; public class GFG { public static void main(String[] args) { // create object of CopyOnWriteArraySet CopyOnWriteArraySet<Integer> ArrSet = new CopyOnWriteArraySet<Integer>(); // Add elements ArrSet.add( 2 ); ArrSet.add( 3 ); ArrSet.add( 3 ); ArrSet.add( 3 ); // print CopyOnWriteArraySet System.out.println( "CopyOnWriteArraySet: " + ArrSet); // 45 is not present hence add System.out.println( "On adding 45 it returns " + ArrSet.add( 45 )); // print CopyOnWriteArraySet System.out.println( "Updated CopyOnWriteArraySet: " + ArrSet); } } |
CopyOnWriteArraySet: [2, 3] On adding 45 it returns true Updated CopyOnWriteArraySet: [2, 3, 45]
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CopyOnWriteArraySet.html#add-E-