What is the ArrayDeque.peekLast method in Java?

Overview

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.

What is the peekLast method of the ArrayDeque?

The peekLast method gets the last element of the ArrayDeque object.

Syntax


public E peekLast()

Parameters

This method doesn’t take any parameters.

Return value

The peekLast() method retrieves the last element of the deque object. If the deque object is empty, then the method returns null.

Code

The code below demonstrates how to use the peekLast method.

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

Explanation

In the code above:

  • Line 1: We import the ArrayDeque class.

  • Line 4: We create an ArrayDeque object with the name arrayDeque.

  • Lines 5 to 7: We use the add() method of the arrayDeque object to add three elements ("1","2","3") to deque.

  • Line 10: We use the peekLast() method of the arrayDeque object to get the last element. In our case, 3 will be returned.

Free Resources