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

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

Java中的 CopyOnWriteArrayList add() 方法

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

句法:

public boolean add(E e)
          or
public void add(int index, E element)

参数:该函数接受两种类型的参数,如下所述:

  • index:指定要添加元素的索引。该参数不是强制性的。如果未传递此参数,则在列表末尾进行添加。
  • element:指定要添加到列表中的元素

返回值:函数在列表中添加时返回true

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

方案一:

// Java Program to illustrate the CopyOnWriteArrayList
// add(element) method in Java
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create object of CopyOnWriteArrayList
        CopyOnWriteArrayList ArrLis
            = new CopyOnWriteArrayList();
  
        // Add elements
        ArrLis.add(2);
        ArrLis.add(3);
        ArrLis.add(4);
        ArrLis.add(7);
  
        // print CopyOnWriteArrayList
        System.out.println("CopyOnWriteArrayList: " + ArrLis);
  
        System.out.println("On adding 45 it returns " 
                                     + ArrLis.add(45));
    }
}
输出:
CopyOnWriteArrayList: [2, 3, 4, 7]
On adding 45 it returns true

方案二:

// Java Program to illustrate the CopyOnWriteArrayList
// add(index, element) method in Java
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create object of CopyOnWriteArrayList
        CopyOnWriteArrayList ArrLis
            = new CopyOnWriteArrayList();
  
        // Add elements at 0th index
        ArrLis.add(0, 2);
        System.out.println("CopyOnWriteArrayList: " + ArrLis);
  
        // Add elements at 0th index
        ArrLis.add(0, 3);
        System.out.println("CopyOnWriteArrayList: " + ArrLis);
  
        // Add elements at 1st index
        ArrLis.add(1, 4);
        System.out.println("CopyOnWriteArrayList: " + ArrLis);
  
        // Add elements at 2nd index
        ArrLis.add(2, 7);
        System.out.println("CopyOnWriteArrayList: " + ArrLis);
    }
}
输出:
CopyOnWriteArrayList: [2]
CopyOnWriteArrayList: [3, 2]
CopyOnWriteArrayList: [3, 4, 2]
CopyOnWriteArrayList: [3, 4, 7, 2]

参考: https: Java/util/concurrent/CopyOnWriteArrayList.html#add-E-