An Deque
interface. ArrayDeque
can be used both as a stack and as a queue. Null elements are prohibited.
element
method of ArrayDeque
?The element
method can be used to get the ArrayDeque
object.
public E element()
This method doesn’t take in any parameters.
This method retrieves the head of the ArrayDeque
object. If the ArrayDeque
object is empty, then NoSuchElementException
error is thrown.
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());}}
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.