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

ConcurrentLinkedDeque is a thread-safe, unbounded deque. The null value is not permitted as an element. We can use the ConcurrentLinkedDeque when multiple threads share a single deque.

The getLast method can be used to get the last element of the ConcurrentLinkedDeque object.

Syntax


public E getLast()

Parameters

This method doesn’t take an argument.

Return value

The getLast method retrieves the last element of the deque object; however, the element is not removed from the deque. If the deque is empty, a NoSuchElementException is thrown.

Here, E is the datatype of the elements held in the deque.

This method is similar to the peekLast method, except the getLast method throws the NoSuchElementException if the deque is empty, whereas the peekLast method returns null.

Code

The code below demonstrates how to use the getLast method.

import java.util.concurrent.ConcurrentLinkedDeque;
class GetLast {
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.getLast() returns : " + deque.getLast());
}
}

Explanation

  • Line 1: We import the ConcurrentLinkedDeque class.

  • Line 4: We create a ConcurrentLinkedDeque object with the name 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 getLast() method of the deque object to get the last element of the deque. In our case, 3 will be returned.

Free Resources