What is the ArrayDeque.element method in Java?
An 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 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
ArrayDequeclass. -
In line 4, we create an
ArrayDequeobject with the namearrayDeque. -
In lines 5 to 7, we use the
add()method of thearrayDequeobject to add three elements ("1","2","3") toarrayDeque. -
In line 10, we use the
element()method of thearrayDequeobject to get the head. In our case,1will be returned.