In Java, element() returns the head of an ArrayDeque without removing it. If the deque is empty, it throws NoSuchElementException.
It comes from the Queue interface and is the same as getFirst(). Its "special value" partner is peek(), which returns null on an empty deque instead.
An instance method of java.util.ArrayDeque (Java 1.6+): a resizable-array deque with no capacity limit, no null elements, and no thread safety.
Syntax
Call element with no arguments.
Java
Queue<String> queue = new ArrayDeque<>();
queue.offer("first");
String head = queue.element(); // "first", still in the queue
Call
What it does
queue.element()
Returns the head; throws if empty.
queue.peek()
Returns the head, or null if empty.
deque.getFirst()
The Deque name for element().
queue.remove()
Returns the head and removes it.
Calling element() twice in a row returns the same object both times, because nothing is removed. Use it when the queue must not be empty at that point in your program.
Library declarations
Java
// java.util.ArrayDeque<E>
public E element()
// Declared in Queue<E> and Deque<E>
Parameters
Parameter
Description
None
element() takes no parameters.
Return Value
Return Value
Description
E
The head of the deque, which stays in place.
Throw or Return a Special Value?
Each end has a method that throws when it cannot work (such as on an empty deque) and one that returnsnull or false instead. The highlighted cell matches element().