addIfAbsent()
如果该元素不在列表中,则该方法将追加该元素。如果元素已经在列表中,则返回FALSE。
语法如下。
public boolean addIfAbsent(E ele)
在这里,ele是要添加到此列表中的元素(如果尚未在列表中)。
要使用CopyOnWriteArrayList类,您需要导入以下程序包。
import java.util.concurrent.CopyOnWriteArrayList;
以下是addIfAbsent()
在Java中实现CopyOnWriteArrayList类方法的示例。
import java.util.concurrent.CopyOnWriteArrayList; public class Demo { public static void main(String[] args) { CopyOnWriteArrayList<Integer> arrList = new CopyOnWriteArrayList<Integer>(); arrList.add(30); arrList.add(40); arrList.add(60); arrList.add(70); arrList.add(90); arrList.add(100); arrList.add(120); System.out.println("CopyOnWriteArrayList = " + arrList); System.out.println("Add an element if not in the List = "+arrList.addIfAbsent(70)); } }
输出结果
CopyOnWriteArrayList = [30, 40, 60, 70, 90, 100, 120] Add an element if not in the List = false
让我们看看另一个示例,其中要添加的元素尚未存在于列表中
import java.util.concurrent.CopyOnWriteArrayList; public class Demo { public static void main(String[] args) { CopyOnWriteArrayList<Integer> arrList = new CopyOnWriteArrayList<Integer>(); arrList.add(30); arrList.add(40); arrList.add(60); arrList.add(70); arrList.add(90); arrList.add(100); arrList.add(120); System.out.println("CopyOnWriteArrayList = " + arrList); System.out.println("Add an element if not in the List = "+arrList.addIfAbsent(150)); System.out.println("Updated CopyOnWriteArrayList = " + arrList); } }
输出结果
CopyOnWriteArrayList = [30, 40, 60, 70, 90, 100, 120] Add an element if not in the List = true Updated CopyOnWriteArrayList = [30, 40, 60, 70, 90, 100, 120, 150]