CopyOnWriteArraySet的add(E e)方法将在参数中传递的元素插入到Set的末尾或Set中的指定索引处。在向Set添加新元素时,该函数返回true。
用法:
public boolean add(E e)
参数:该函数接受单个强制性参数element ,该元素指定要添加到集合中的元素。
返回值:该函数在添加Set时返回true。
以下示例程序旨在说明上述函数:
示例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]
示例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]
参考: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CopyOnWriteArraySet.html#add-E-
注:本文由纯净天空筛选整理自 CopyOnWriteArraySet add() method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。