Stack using ArrayDeque class in Java
Stack is a linear data structure which follows the Last-In-First-Out (LIFO) approach, where the last element inserted is the first one to be removed.
In this post, we’ll see how to implement a stack using ArrayDeque — a resizable array implementation of the Deque interface. Java provides the ArrayDeque class as part of the Java Collections Framework. For an overview of the Java Collections Framework, check out my post Overview of the Java Collections Framework.
Some important methods in the ArrayDeque class are:
- push(E element)
- pop()
- peek()
- isEmpty()
Array deques have no capacity restrictions, which means they grow as necessary to support usage.
ArrayDeque class prohibits null
elements. Even if it had allowed, it is not recommended to insert nulls because null
is used as a special return value by various methods to indicate that the deque is empty.
According to Java Docs, ArrayDeque class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue.
The following example demonstrates how to implement a stack using the ArrayDeque class.
Example
Output
Let us carefully look at the methods used in the above program.
Methods
1) push(E element)
This method pushes an element onto the stack represented by this deque. In other words, it inserts the element at the front of this deque.
If the specified element is null
, a 'NullPointerException'
is thrown.
Consider a stack with the following elements from top: “Banana” “Apple”
This method pushes the string “Orange” to the top of the stack. Now, the elements in the stack are: “Orange” “Banana” “Apple”
2) pop()
This method pops an element from the stack represented by this deque. In other words, it removes and returns the first element of this deque.
If the stack is empty, a ‘NoSuchElementException’
exception is thrown.
This method removes and returns the string “Orange” which is at the top of the stack.
3) peek()
It retrieves, but does not remove, the head of the queue represented by this deque. If the deque is empty, it returns null
. As the name indicates, it is similar to peeking at the top of the stack.
This call to the method returns the string “Banana” which is at the top of the stack, but doesn’t remove it from the stack.
4) isEmpty()
This method tests if the stack is empty. It returns true if the stack is empty or false otherwise.
The above while
loop continues to execute until the stack is empty.
Now since you know how to implement a stack using the ArrayDeque class, check out other ways to create a stack: