What is the ArrayDeque.getFirst 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 both Stack or Queue. Null elements are prohibited.

What is the getFirst method of the ArrayDeque?

The getFirst method can be used to get the first element of the ArrayDeque object.

Syntax


public E getFirst()

Parameters

This method doesn’t take an argument.

Return value

This method retrieves the first element of the deque object. If the deque is empty, then NoSuchElementException is. thrown.

This method is similar to the peekFirst method except that the getFirst method throws the NoSuchElementException if the deque is empty whereas the peekFirst method returns null.

Code

The code below demonstrates how to use the getFirst method.

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

Explanation

  • Line 1: We imported the ArrayDeque class.

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

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

  • Line 10: We used the getFirst() method of the arrayDeque object to get the first element of the deque. In our case, 1 will be returned.

Free Resources