An
This class is the implementation class of the Deque
interface. ArrayDeque
can be used as both Stack or Queue. Null
elements are prohibited.
getFirst
method of the ArrayDeque
?The getFirst
method can be used to get the first element of the ArrayDeque
object.
public E getFirst()
This method doesn’t take an argument.
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
peekFirst
method except that thegetFirst
method throws theNoSuchElementException
if thedeque
is empty whereas thepeekFirst
method returnsnull
.
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());}}
Line 1: We imported the ArrayDeque
class.
Line 4: We created an ArrayDeque
object with the name arrayDeque
.
Lines 5 to 7: We used the add()
method of the arrayDeque
object to add three elements ("1"
,"2"
,"3"
) to deque
.
Line 10: We used the getFirst()
method of the arrayDeque
object to get the first element of the deque
. In our case, 1
will be returned.