Java Deque element() Method Tutorial

In this section, we will learn what the Deque element() method is and how to use it in Java.

What is Java Deque element() Method?

The Java Deque element() method is used to get the first (head) element of a Deque object.

Note: this element just returns a copy of the first (head) element of a Deque object, but it does not remove that head element.

Java element() Method Syntax:

E element()

element() Method Parameters:

The method does not throw an exception.

element() Method Return Value:

The return value of this method is the first (head) element of the target Deque object.

element() Method Exceptions:

The method might throw one exception and that is:

NoSuchElementException: We get this exception if the target Deque object was in fact empty!

Example: using Deque element() method

import java.util.Deque;
import java.util.ArrayDeque;
class Main{
    public static void main(String[] args) {
        Deque<Integer> deque = new ArrayDeque<>();
        deque.add(1);
        deque.add(2);
        deque.add(3);
        deque.add(0);
        deque.add(10);

        System.out.println("The size of a deque object before calling the element() method: "+deque.size());
        System.out.println("Getting the first element of a deque object using the element() method: "+ deque.element());
        System.out.println("Now the size of that deque object after calling the element() method: "+deque.size());
    }
        
}

Output:

The size of a deque object before calling the element() method: 5

Getting the first element of a deque object using the element() method: 1

Now the size of that deque object after calling the element() method: 5
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies