📌  相关文章
📜  Java中的 ConcurrentLinkedDeque addFirst() 方法

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

Java中的 ConcurrentLinkedDeque addFirst() 方法

Java .util.concurrent.ConcurrentLinkedDeque.addFirst()是Java中的一个内置函数,它在 ConcurrentLinkedDeque 的前面插入指定的元素。

句法:

conn_linked_deque.addFirst(elem)

参数:该方法仅接受要添加到 ConcurrentLinkedDeque 开头的单个参数elem

返回值:该函数没有返回值。

异常:当传递给函数的参数为 null时,该方法将抛出NullPointerException 。由于其有界性质,此方法永远不会抛出IllegalStateException或返回 false。

下面的程序说明了 ConcurrentLinkedDeque.addFirst() 方法:

方案 1:该方案涉及 Integer 类型的 ConcurrentLinkedDeque。

// Java Program Demonstrate addFirst()
// method of ConcurrentLinkedDeque 
  
import java.util.concurrent.*;
  
class ConcurrentLinkedDequeDemo {
    public static void main(String[] args)
    {
        ConcurrentLinkedDeque cld = 
                     new ConcurrentLinkedDeque();
  
        cld.addFirst(12);
        cld.addFirst(110);
        cld.addFirst(55);
        cld.addFirst(76);
  
        // Displaying the existing LinkedDeque
        System.out.println("Initial Elements in"
                           + "the LinkedDeque: " + cld);
  
        // Insert a new element in the  LinkedDeque
        cld.addFirst(21);
  
        // Displaying the modified LinkedDeque
        System.out.println("Initial Elements in"
                           + "the LinkedDeque: " + cld);
    }
}
输出:
Initial Elements inthe LinkedDeque: [76, 55, 110, 12]
Initial Elements inthe LinkedDeque: [21, 76, 55, 110, 12]

程序 2:该程序涉及一个 Integer 类型的 ConcurrentLinkedDeque,当null作为参数传递给函数时具有异常处理。

// Java Program Demonstrate addFirst()
// method of ConcurrentLinkedDeque 
  
import java.util.concurrent.*;
  
class ConcurrentLinkedDequeDemo {
    public static void main(String[] args)
    {
        ConcurrentLinkedDeque cld = 
                         new ConcurrentLinkedDeque();
  
        cld.addFirst("Geeks");
        cld.addFirst("Geek");
        cld.addFirst("Gfg");
        cld.addFirst("Contribute");
  
        // Displaying the existing LinkedDeque
        System.out.println("Initial Elements in"
                           + "the LinkedDeque: " + cld);
  
        /* Exception thrown when null 
             is passed as parameter*/
        try {
            cld.addFirst(null);
        }
        catch (NullPointerException e) {
            System.out.println("NullPointerException"
                               + "thrown");
        }
  
        // Insert a new element in the  LinkedDeque
        cld.addFirst("Sudo Placement");
  
        // Displaying the modified LinkedDeque
        System.out.println("Initial Elements in"
                           + "the LinkedDeque: " + cld);
    }
}
输出:
Initial Elements inthe LinkedDeque: [Contribute, Gfg, Geek, Geeks]
NullPointerExceptionthrown
Initial Elements inthe LinkedDeque: [Sudo Placement, Contribute, Gfg, Geek, Geeks]

参考: https: Java/util/concurrent/ConcurrentLinkedDeque.html#addFirst()