📌  相关文章
📜  Java中的 LinkedBlockingDeque removeFirst() 方法

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

Java中的 LinkedBlockingDeque removeFirst() 方法

LinkedBlockingDequeremoveFirst()方法返回并从中删除 Deque 容器的第一个元素。如果 Deque 容器为空,该方法将引发NoSuchElementException

句法:

public E removeFirst()

返回:此方法返回 Deque 容器的头部,即第一个元素。

异常:如果双端队列为空,该函数将抛出NoSuchElementException

下面的程序说明了 LinkedBlockingDeque 的 removeFirst() 方法:

方案一:

// Java Program to demonstrate removeFirst()
// method of LinkedBlockingDeque
  
import java.util.concurrent.LinkedBlockingDeque;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
        throws InterruptedException
    {
  
        // create object of LinkedBlockingDeque
        LinkedBlockingDeque LBD
            = new LinkedBlockingDeque();
  
        // Add numbers to end of LinkedBlockingDeque
        LBD.add(7855642);
        LBD.add(35658786);
        LBD.add(5278367);
        LBD.add(74381793);
  
        // print Dequee
        System.out.println("Linked Blocking Deque: " + LBD);
  
        // removes the front element and prints it
        System.out.println("First element of Linked Blocking Deque: "
                           + LBD.removeFirst());
  
        // prints the Deque
        System.out.println("Linked Blocking Deque: " + LBD);
    }
}
输出:
Linked Blocking Deque: [7855642, 35658786, 5278367, 74381793]

First element of Linked Blocking Deque: 7855642

Linked Blocking Deque: [35658786, 5278367, 74381793]

方案二:

// Java Program to demonstrate removeFirst()
// method of LinkedBlockingDeque
  
import java.util.concurrent.LinkedBlockingDeque;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
        throws NoSuchElementException
    {
  
        // create object of LinkedBlockingDeque
        LinkedBlockingDeque LBD
            = new LinkedBlockingDeque();
  
        // print Dequee
        System.out.println("Linked Blocking Deque: " + LBD);
  
        try {
            // throws an exception
            LBD.removeFirst();
        }
        catch (Exception e) {
            System.out.println("Exception when removing "
                               + "first element from this Deque: "
                               + e);
        }
    }
}
输出:
Linked Blocking Deque: []
Exception when removing first element from this Deque: java.util.NoSuchElementException

参考: https: Java/util/concurrent/LinkedBlockingDeque.html#removeFirst–