An Deque
interface.
ArrayDeque
can be used as both a stack or queue.Null
elements are prohibited.
peek
method?The peek
method of the ArrayDeque
class can be used to get the ArrayDeque
object.
public E peek()
This method doesn’t take any argument.
This method retrieves the deque
object. If the deque
object is empty, then null
is returned.
The code below demonstrates how to use the peek
method.
import java.util.ArrayDeque;class Peek {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.peek() returns : " + arrayDeque.peek());}}
In the code above:
In line 1, we imported the ArrayDeque
class.
In line 4, we created an ArrayDeque
object with the name arrayDeque
.
From lines 5 to 7, we used the add()
method of the arrayDeque
object to add three elements ("1","2","3"
) to deque
.
In line 10, we used the peek()
method of the arrayDeque
object to get the deque
. In our case, 1
will be returned.