Stack Using Deque in Java
Problem
Deque already defines push(), pop(), and peek() with exact stack semantics, so ArrayDeque can act as a stack directly — no separate Stack class is needed.
Push a few elements onto an ArrayDeque used as a stack, then pop and peek to confirm last-in-first-out order.
Java Program
import java.util.ArrayDeque;
import java.util.Deque;
public class StackUsingDeque {
public static void main(String[] args) {
Deque<String> stack = new ArrayDeque<>();
stack.push("first");
stack.push("second");
stack.push("third"); // most recently pushed — now on top
System.out.println("Top: " + stack.peek());
System.out.println("Pop: " + stack.pop());
System.out.println("Pop: " + stack.pop());
System.out.println("Remaining top: " + stack.peek());
}
}Output
Core Logic
Declaring the variable as a Deque and backing it with ArrayDeque gets the exact same push/pop/peek stack behavior the legacy Stack class offers, without any of Stack's baggage.
- 1
Deque<String> stack = new ArrayDeque<>();declares the variable by its interface, backed by ArrayDeque. - 2
push("first"),push("second"),push("third")each add to the same end, so the most recently pushed element is always on top. - 3
peek()reads the top element without removing it —"third", the last one pushed. - 4
pop()removes and returns the top element each time — first"third", then"second"— leaving"first"as the new top.
Key Point: The JDK's own documentation recommends ArrayDeque over java.util.Stack for stack usage today — Stack is a legacy class that extends the little-used Vector and carries synchronization overhead nothing here actually needs, while ArrayDeque is unsynchronized and generally faster.
Why: push(), pop(), and peek() each work on one end of the backing resizable array in amortized constant time, while the stack holds up to n elements at once.