What is the ArrayDeque.peekFirst method in Java?
An Deque interface. ArrayDeque can be used as a stack or queue. Null elements are prohibited.
The peekFirst method
The peekFirst method can be used to get the first element of the ArrayDeque object.
Note: The
peekfirst()method does not remove the first element from the deque.
Syntax
public E peekFirst()
Parameters
This method does not take any parameters.
Return value
The peekFirst method retrieves the first element of the deque object. If the deque object is empty, then peekFirst returns null.
Code
The code below demonstrates how to use the peekFirst method.
import java.util.ArrayDeque;class PeekFirst {public static void main( String args[] ) {ArrayDeque<String> arrayDeque = new ArrayDeque<>();arrayDeque.add("1");arrayDeque.add("2");arrayDeque.add("3");System.out.println("The arrayDeque is " + arrayDeque);System.out.println("arrayDeque.peekFirst() returns : " + arrayDeque.peekFirst());}}
Explanation
In the code above:
-
In line 1, we import the
ArrayDequeclass. -
In line 4, we create an
ArrayDequeobject with the namearrayDeque. -
In lines 5 to 7, we use the
add()method of thearrayDequeobject to add three elements ("1","2","3") toarrayDeque. -
In line 10, we use the
peekFirst()method of thearrayDequeobject to get the first element. In our case,1will be returned.