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


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


java.util.concurrent.ConcurrentLinkedDeque.offer()方法是Java中的內置方法,它將作為參數傳遞的指定元素插入雙端隊列。

用法:

public boolean offer(E elem)

參數:該方法接受參數elem,以選擇要插入雙端隊列的元素。


返回值:如果將元素成功添加到雙端隊列中,則該函數返回True,否則返回False。

異常:如果傳遞的參數為NULL,則該函數將引發NullPointerException。

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

程序1

// Java Program to Demonstrate offer() 
// method of ConcurrentLinkedDeque 
  
import java.util.concurrent.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // Creating an empty Deque 
        ConcurrentLinkedDeque<String> cld 
            = new ConcurrentLinkedDeque<String>(); 
  
        // Add elements into the Deque 
        cld.add("Welcome"); 
        cld.add("To"); 
        cld.add("Geeks"); 
        cld.add("4"); 
        cld.add("Geeks"); 
  
        // Displaying the Deque 
        System.out.println("ConcurrentLinkedDeque: "
                           + cld); 
  
        // Insert an element using offer() 
        if (cld.offer("GFG")) { 
  
            // Displaying message 
            System.out.println("Element Inserted"); 
        } 
        else { 
  
            // Displaying message 
            System.out.println("Element not Inserted"); 
        } 
  
        // Displaying the Deque 
        System.out.println("ConcurrentLinkedDeque: "
                           + cld); 
    } 
}
輸出:
ConcurrentLinkedDeque: [Welcome, To, Geeks, 4, Geeks]
Element Inserted
ConcurrentLinkedDeque: [Welcome, To, Geeks, 4, Geeks, GFG]
// Java Program to Demonstrate offer() 
// method of ConcurrentLinkedDeque 
  
import java.util.concurrent.*; 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // Creating an empty Deque 
        ConcurrentLinkedDeque<String> cld 
            = new ConcurrentLinkedDeque<String>(); 
  
        // Add elements into the Deque 
        cld.add("Welcome"); 
        cld.add("To"); 
        cld.add("Geeks"); 
        cld.add("4"); 
        cld.add("Geeks"); 
  
        // Displaying the Deque 
        System.out.println("ConcurrentLinkedDeque: "
                           + cld); 
  
        try { 
  
            // Insert null element using offer() 
            cld.offer(null); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}
輸出:
ConcurrentLinkedDeque: [Welcome, To, Geeks, 4, Geeks]
java.lang.NullPointerException

參考: https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/ConcurrentLinkedDeque.html#offer-E-



相關用法


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