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

What is the element method of ArrayDeque?

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

Syntax

public E element()

Parameters

This method doesn’t take in any parameters.

Return value

This method retrieves the head of the ArrayDeque object. If the ArrayDeque object is empty, then NoSuchElementException error is thrown.

Code

The code below demonstrates how to use the element method.

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

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 element() method of the arrayDeque object to get the head. In our case, 1 will be returned.

Free Resources