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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。