CopyOnWriteArrayList的add(E e)方法將在參數中傳遞的元素插入到列表的末尾或列表中的指定索引處。向列表中添加新元素時,該函數返回true。
用法:
public boolean add(E e) or public void add(int index, E element)
參數:該函數接受兩種類型的參數,如下所述:
- index:指定要添加元素的索引。該參數不是必需的。如果未傳遞此參數,則添加將在列表末尾進行。
- element:指定要添加到列表中的元素
返回值:該函數在列表中添加後返回true。
以下示例程序旨在說明上述函數:
示例1:
// 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<Integer> ArrLis
= new CopyOnWriteArrayList<Integer>();
// 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
示例2:
// 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<Integer> ArrLis
= new CopyOnWriteArrayList<Integer>();
// 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://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CopyOnWriteArrayList.html#add-E-
相關用法
- Java CopyOnWriteArrayList get()用法及代碼示例
- Java CopyOnWriteArrayList contains()用法及代碼示例
- Java CopyOnWriteArrayList indexOf()用法及代碼示例
- Java CopyOnWriteArrayList hashCode()用法及代碼示例
- Java CopyOnWriteArrayList lastIndexOf()用法及代碼示例
- Java CopyOnWriteArrayList set()用法及代碼示例
- Java CopyOnWriteArrayList toArray()用法及代碼示例
- Java CopyOnWriteArrayList spliterator()用法及代碼示例
- Java CopyOnWriteArrayList toString()用法及代碼示例
- Java CopyOnWriteArrayList size()用法及代碼示例
- Java CopyOnWriteArrayList containsAll()用法及代碼示例
- Java CopyOnWriteArrayList listIterator()用法及代碼示例
- Java CopyOnWriteArrayList iterator()用法及代碼示例
- Java CopyOnWriteArrayList addIfAbsent()用法及代碼示例
- Java CopyOnWriteArrayList isEmpty()用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 CopyOnWriteArrayList add() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。