📌  相关文章
📜  Java中的 CopyOnWriteArraySet add() 方法

📅  最后修改于: 2022-05-13 01:54:42.832000             🧑  作者: Mango

Java中的 CopyOnWriteArraySet add() 方法

CopyOnWriteArraySetadd(E e)方法将参数中传递的元素插入到 Set 的末尾或 Set 中的指定索引处。该函数在将新元素添加到 Set 时返回 true。

句法:

public boolean add(E e)

参数:该函数接受一个强制参数元素,该元素指定要添加到集合中的元素。

返回值:该函数在 Set 中添加时返回true

下面的程序说明了上述函数:

方案一:

// 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 ArrSet
            = new CopyOnWriteArraySet();
  
        // 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]

方案二:

// 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 ArrSet
            = new CopyOnWriteArraySet();
  
        // 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: Java/util/concurrent/CopyOnWriteArraySet.html#add-E-