What is the ArrayDeque.peek 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 both a stack or queue. Null elements are prohibited.

What is the peek method?

The peek method of the ArrayDequeclass can be used to get the headfirst element of the ArrayDeque object.

Syntax

public E peek()

Parameters

This method doesn’t take any argument.

Return value

This method retrieves the headfirst element of the deque object. If the deque object is empty, then null is returned.

Code

The code below demonstrates how to use the peek method.

import java.util.ArrayDeque;
class Peek {
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.peek() returns : " + arrayDeque.peek());
}
}

Explanation

In the code above:

  • In line 1, we imported the ArrayDeque class.

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

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

  • In line 10, we used the peek() method of the arrayDeque object to get the headfirst element of the deque. In our case, 1 will be returned.

Free Resources