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

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

Java中的 CopyOnWriteArrayList addIfAbsent() 方法

如果元素不存在于列表中, CopyOnWriteArrayListaddIfAbsent(E e)方法会将参数中传递的元素附加到列表的末尾。该函数在将新元素添加到列表时返回 true。

句法:

public boolean addIfAbsent(E e)

参数:该函数接受单个强制参数元素,该元素指定要附加到列表中的元素(如果不存在)。

返回值:如果添加到列表中,该函数返回true

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

方案一:

// 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 ArrLis
            = new CopyOnWriteArrayList();
  
        // 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

方案二:

// 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 ArrLis
            = new CopyOnWriteArrayList();
  
        // 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: Java/util/concurrent/CopyOnWriteArrayList.html#addIfAbsent-E-