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


Java Deque offerFirst()用法及代碼示例


如果可以在不違反容量限製的情況下立即執行此操作,則Deque Interface的offerFirst(E e)方法會將指定的元素插入Deque的前麵。此方法優於addFirst()方法,因為在容器的容量已滿時,此方法不會引發異常,因為它會返回false。

用法:

boolean offerFirst(E e)

參數:此方法接受強製性參數e,該參數是要插入到雙端隊列的前麵的元素。

返回:成功插入時此方法返回true,否則返回false。

異常:該函數引發四個異常,如下所述:



  • ClassCastException:當要輸入的元素的類阻止將其添加到此容器中時:
  • IllegalArgumentException:當元素的某些屬性阻止將其添加到雙端隊列時。
  • NullPointerException :當要插入的元素作為null傳遞並且Deque的接口不允許使用null元素時:

以下示例程序旨在說明Deque的offerFirst()方法:

程序1:

// Java Program Demonstrate offerFirst() 
// method of Deque when Null is passed 
import java.util.*; 
import java.util.concurrent.LinkedBlockingDeque; 
  
public class GFG { 
    public static void main(String[] args) 
        throws IllegalStateException 
    { 
  
        // create object of Deque 
        Deque<Integer> DQ 
            = new LinkedBlockingDeque<Integer>(3); 
  
        if (DQ.offerFirst(10)) 
            System.out.println("The Deque is not full and 10 is inserted"); 
        else
            System.out.println("The Deque is full"); 
  
        if (DQ.offerFirst(15)) 
            System.out.println("The Deque is not full and 15 is inserted"); 
        else
            System.out.println("The Deque is full"); 
  
        if (DQ.offerFirst(25)) 
            System.out.println("The Deque is not full and 25 is inserted"); 
        else
            System.out.println("The Deque is full"); 
  
        if (DQ.offerFirst(20)) 
            System.out.println("The Deque is not full and 20 is inserted"); 
        else
            System.out.println("The Deque is full"); 
  
        // before removing print Deque 
        System.out.println("Deque:" + DQ); 
    } 
}
輸出:
The Deque is not full and 10 is inserted
The Deque is not full and 15 is inserted
The Deque is not full and 25 is inserted
The Deque is full
Deque:[25, 15, 10]

程序2:

// Java Program Demonstrate offerFirst() 
// method of Queue when Null is passed 
import java.util.*; 
import java.util.concurrent.LinkedBlockingDeque; 
  
public class GFG { 
    public static void main(String[] args) 
        throws NullPointerException 
    { 
  
        // create object of Queue 
        Deque<Integer> DQ 
            = new LinkedBlockingDeque<Integer>(); 
  
        // Add numbers to end of Deque 
        DQ.offerFirst(7855642); 
        DQ.offerFirst(35658786); 
        DQ.offerFirst(5278367); 
  
        // when null is inserted 
        DQ.offerFirst(null); 
  
        // before removing print Deque 
        System.out.println("Deque:" + DQ); 
    } 
}

輸出:

Exception in thread "main" java.lang.NullPointerException
    at java.util.concurrent.LinkedBlockingDeque.offerFirst(LinkedBlockingDeque.java:342)
    at GFG.main(GFG.java:21)

注意:其他兩個異常是內部的,它們是由編譯器引起的,因此無法在代碼中顯示。

參考: https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html#offerFirst-E-

相關用法


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