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
peekLastmethod, except thegetLastmethod throws theNoSuchElementExceptionif thedequeis empty, whereas thepeekLastmethod returnsnull.
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
ConcurrentLinkedDequeclass. -
Line 4: We create a
ConcurrentLinkedDequeobject with the namedeque. -
Lines 5 to 7: We use the
add()method of thedequeobject to add three elements ("1","2","3") todeque. -
Line 10: We use the
getLast()method of thedequeobject to get the last element of thedeque. In our case,3will be returned.