What is the ArrayDeque.getFirst method in Java?
Overview
An
This class is the implementation class of the Deque interface. ArrayDeque can be used as both Stack or Queue. Null elements are prohibited.
What is the getFirst method of the ArrayDeque?
The getFirst method can be used to get the first element of the ArrayDeque object.
Syntax
public E getFirst()
Parameters
This method doesn’t take an argument.
Return value
This method retrieves the first element of the deque object. If the deque is empty, then NoSuchElementException is. thrown.
This method is similar to the
peekFirstmethod except that thegetFirstmethod throws theNoSuchElementExceptionif thedequeis empty whereas thepeekFirstmethod returnsnull.
Code
The code below demonstrates how to use the getFirst method.
import java.util.ArrayDeque;class GetFirst {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.getFirst() returns : " + arrayDeque.getFirst());}}
Explanation
-
Line 1: We imported the
ArrayDequeclass. -
Line 4: We created an
ArrayDequeobject with the namearrayDeque. -
Lines 5 to 7: We used the
add()method of thearrayDequeobject to add three elements ("1","2","3") todeque. -
Line 10: We used the
getFirst()method of thearrayDequeobject to get the first element of thedeque. In our case,1will be returned.