What is the ArrayDeque.peekFirst method in Java?

An ArrayDequeArray Double Ended Queue is a growable array that allows us to add or remove an element from both the front and back. This class is the implementation class of the 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 ArrayDeque class.

  • In line 4, we create an ArrayDeque object with the name arrayDeque.

  • In lines 5 to 7, we use the add() method of the arrayDeque object to add three elements ("1","2","3") to arrayDeque.

  • In line 10, we use the peekFirst() method of the arrayDeque object to get the first element. In our case, 1 will be returned.

Free Resources