What is the ArrayDeque.getLast method in Java?
The getLast method is used to get the last element of the ArrayDeque object without deleting the item itself.
An
ArrayDeque(Array Double Ended Queue) is a growable array that allows us to add or remove an element from both the front and back. This class is the implementation class of theDequeinterface.ArrayDequecan be used as a stack or queue.Nullelements are prohibited.
Syntax
public E getLast()
Parameters
This method doesn’t take any parameters.
Return value
The getLast method retrieves the last element of the deque object. If the dequeu is empty then the NoSuchElementException exception is thrown.
This method is similar to the
peekLastmethod except that thegetLastmethod throws theNoSuchElementExceptionif thedequeis empty whereas thepeekLastmethod returnsnull.
Code
The code below demonstrates how to use the getLast method.
import java.util.ArrayDeque;class GetLast {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.getLast() returns : " + arrayDeque.getLast());}}
Explanation
In the code above:
-
In line 1: We import the
ArrayDequeclass. -
In line 4: We create an
ArrayDequeobject with the namearrayDeque. -
From lines 5 to 7: We use the
add()method of thearrayDequeobject to add three elements ("1","2","3") todequeu. -
In line 10: We use the
getLast()method of thearrayDequeobject to get the last element of thedeque. In our case,3is returned.