當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java ConcurrentLinkedDeque add()用法及代碼示例


java.util.concurrent.ConcurrentLinkedDeque.add()是Java中的內置函數,它將指定的元素插入雙端隊列的末尾。

用法:

conn_linked_deque.add(elem)

參數:該方法僅接受要添加到ConcurentLinkedDeque尾部的單個參數elem。


返回值:該函數沒有返回值。

異常:當傳遞給函數的參數為​​null時,該方法將引發NullPointerException。由於其有限的性質,此方法將永遠不會引發IllegalStateException或返回false。

以下示例程序旨在說明ConcurrentLinkedDeque.add()方法:

示例1:該程序涉及一個Integer類型的ConcurrentLinkedDeque。

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

示例2:當將null作為參數傳遞給函數時,此程序涉及String類型的ConcurrentLinkedDeque和異常處理。

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

參考: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentLinkedDeque.html#add()



相關用法


注:本文由純淨天空篩選整理自RICHIK BHATTACHARJEE大神的英文原創作品 ConcurrentLinkedDeque add() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。