Java中的 ArrayDeque peekFirst() 方法
Java中的Java .util.ArrayDeque.peekFirst() 方法用于检索或获取双端队列的第一个元素。检索到的元素不会从队列中删除或移除,而是该方法只是返回它。如果双端队列中不存在任何元素或者它为空,则返回 Null。
句法:
Array_Deque.peekFirst()
参数:该方法不带任何参数。
返回值:该方法返回 Deque 的第一个元素。
下面的程序说明了Java.util.ArrayDeque.peekFirst() 方法:
方案一:
// Java code to illustrate peekFirst()
import java.util.*;
public class ArrayDequeDemo {
public static void main(String args[])
{
// Creating an empty ArrayDeque
Deque de_que = new ArrayDeque();
// Use add() method to add elements into the Deque
de_que.add("Welcome");
de_que.add("To");
de_que.add("Geeks");
de_que.add("4");
de_que.add("Geeks");
// Displaying the ArrayDeque
System.out.println("Initial ArrayDeque: " + de_que);
// Displaying the first element
System.out.println("The first element is: " +
de_que.peekFirst());
// Displaying the ArrayDeque after operation
System.out.println("Final ArrayDeque: " + de_que);
}
}
输出:
Initial ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
The first element is: Welcome
Final ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
方案二:
// Java code to illustrate peekFirst()
import java.util.*;
public class ArrayDequeDemo {
public static void main(String args[])
{
// Creating an empty ArrayDeque
Deque de_que = new ArrayDeque();
// Use add() method to add elements into the Deque
de_que.add(10);
de_que.add(15);
de_que.add(30);
de_que.add(20);
de_que.add(5);
// Displaying the ArrayDeque
System.out.println("Initial ArrayDeque: " + de_que);
// Displaying the first element
System.out.println("The first element is: " +
de_que.peekFirst());
// Displaying the ArrayDeque after operation
System.out.println("Final ArrayDeque: " + de_que);
}
}
输出:
Initial ArrayDeque: [10, 15, 30, 20, 5]
The first element is: 10
Final ArrayDeque: [10, 15, 30, 20, 5]
程序 3:对于一个空的双端队列:
// Java code to illustrate peekFirst()
import java.util.*;
public class ArrayDequeDemo {
public static void main(String args[])
{
// Creating an empty ArrayDeque
ArrayDeque de_que = new ArrayDeque();
// Displaying the ArrayDeque
System.out.println("ArrayDeque: " + de_que);
// Displaying the first element
System.out.println("The first element is: " +
de_que.peekFirst());
}
}
输出:
ArrayDeque: []
The first element is: null