當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java CopyOnWriteArraySet add()用法及代碼示例


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。