Java中的 LinkedBlockingDeque getFirst() 方法
LinkedBlockingDeque的getFirst()方法返回 Deque 容器中最前面的元素。如果 LinkedBlockingDeque 为空,则在函数调用时返回NoSuchElementException 。
句法:
public E getLast()
参数:此方法不接受任何参数。
返回:此方法返回此 Deque 容器的第一个元素或头部。
异常:当双端队列为空时,该函数仅抛出一个异常,即NoSuchElementException
下面的程序说明了 LinkedBlockingDeque 的 getFirst() 方法:
方案一:
// Java Program Demonstrate getFirst()
// method of LinkedBlockingDeque
import java.util.concurrent.LinkedBlockingDeque;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws IllegalStateException
{
// create object of LinkedBlockingDeque
LinkedBlockingDeque LBD
= new LinkedBlockingDeque();
// Add numbers to front of LinkedBlockingDeque
LBD.addFirst(7855642);
LBD.addFirst(35658786);
LBD.addFirst(5278367);
LBD.addFirst(74381793);
// before removing print queue
System.out.println("Linked Blocking Deque: " + LBD);
// prints the first element
System.out.println("Linked Blocking Deque first element: " +
LBD.getFirst());
}
}
输出:
Linked Blocking Deque: [74381793, 5278367, 35658786, 7855642]
Linked Blocking Deque first element: 74381793
方案二:
// Java Program Demonstrate getFirst()
// method of LinkedBlockingDeque
import java.util.concurrent.LinkedBlockingDeque;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws IllegalStateException
{
// create object of LinkedBlockingDeque
LinkedBlockingDeque LBD
= new LinkedBlockingDeque();
// Add numbers to front of LinkedBlockingDeque
LBD.addFirst(7855642);
LBD.addFirst(35658786);
LBD.addFirst(5278367);
LBD.addFirst(74381793)
LBD.clear();
// Since the container is empty it will throw exception
System.out.println("Linked Blocking Deque first element: " +
LBD.getFirst());
}
}
输出:
Exception in thread "main" java.util.NoSuchElementException
at java.util.concurrent.LinkedBlockingDeque.getFirst(LinkedBlockingDeque.java:553)
at GFG.main(GFG.java:28)
参考: https: Java/util/concurrent/LinkedBlockingDeque.html#getFirst()