What is the ConcurrentLinkedDeque.element() method in Java?

Overview

The element() method in Java retrieves the headfirst element of the ConcurrentLinkedDeque object.

ConcurrentLinkedDeque is a thread-safe, unbounded deque.

A null value is not permitted as an element.

We use ConcurrentLinkedDeque when multiple threads share a single deque.

Syntax

public E element()

Parameters

This method doesn’t take in any parameters.

Return value

The element() method retrieves the head of the deque. If the deque is empty, NoSuchElementException is thrown.

This method is similar to the peek method, except the peek method returns null instead of NoSuchElementException.

Code

The code below demonstrates how to use the element() method.

import java.util.concurrent.ConcurrentLinkedDeque;
class Element {
public static void main( String args[] ) {
ConcurrentLinkedDeque<String> deque = new ConcurrentLinkedDeque<>();
deque.add("1");
deque.add("2");
deque.add("3");
System.out.println("The deque is " + deque);
System.out.println("deque.element() returns : " + deque.element());
}
}

Explanation

  • Line 1: We import the ConcurrentLinkedDeque class.

  • Line 4: We create a ConcurrentLinkedDeque object named deque.

  • Lines 5 to 7: We use the add() method of the deque object to add three elements ("1","2","3") to deque.

  • Line 10: We use the element() method of the deque object to get the head. In this case, 1 is returned.

Free Resources