Java CopyOnWriteArrayList addIfAbsent()方法
CopyOnWriteArrayList 的 addIfAbsent(E e) 方法在列表中不存在的情况下,将参数中的元素追加到列表的末尾。当新元素被添加到列表中时,该函数返回true。
语法
public boolean addIfAbsent(E e)
参数: 该函数接受一个强制参数 元素 ,如果该元素不存在,则指定将其追加到列表中。
返回值: 如果它被添加到列表中,该函数返回true。
下面的程序说明了上述函数。
程序1 :
// Java Program to illustrate the CopyOnWriteArrayList
// addIfAbsent(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.addIfAbsent(2);
ArrLis.addIfAbsent(3);
ArrLis.addIfAbsent(4);
ArrLis.addIfAbsent(7);
// print CopyOnWriteArrayList
System.out.println("CopyOnWriteArrayList: "
+ ArrLis);
System.out.println("On adding 4 it returns "
+ ArrLis.addIfAbsent(4) + " as it is present");
}
}
输出。
CopyOnWriteArrayList: [2, 3, 4, 7]
On adding 4 it returns false as it is present
程序2
// Java Program to illustrate the CopyOnWriteArrayList
// addIfAbsent(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<String> ArrLis
= new CopyOnWriteArrayList<String>();
// Add elements
ArrLis.addIfAbsent("gopal");
ArrLis.addIfAbsent("gfg");
ArrLis.addIfAbsent("jgec");
ArrLis.addIfAbsent("sudo");
// print CopyOnWriteArrayList
System.out.println("CopyOnWriteArrayList: " + ArrLis);
System.out.println("On adding 'sudo' it returns "
+ ArrLis.addIfAbsent("sudo") + " as it is present");
}
}
输出。
CopyOnWriteArrayList: [gopal, gfg, jgec, sudo]
On adding 'sudo' it returns false as it is present
参考资料: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CopyOnWriteArrayList.html#addIfAbsent-E-