01 / 21

Deque as Stack

Master the modern, recommended way to implement a stack in Java using ArrayDeque: push, pop, and peek with confidence.

Java

What Is a Stack?

A stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle: the most recently added element is the first one removed.

"A" "B" "C" TOP (last in) BOTTOM (first in) LIFO

Three Core Operations

push(e)
Add element e to the top of the stack.
pop()
Remove and return the element at the top.
peek()
Return the top element without removing it.

Why Not java.util.Stack?

The legacy Stack class extends Vector, which means every operation is synchronized (thread-safe locking), adding unnecessary overhead for single-threaded programs.

1
Synchronized overhead: Vector locks on every call, even when no other thread is accessing the stack.
2
Broken abstraction: Stack inherits Vector's random-access methods like get(i) and add(i, e), breaking the LIFO contract.
3
Official guidance: The Java docs state: "A more complete and consistent set of LIFO stack operations is provided by the Deque interface."

Enter ArrayDeque

ArrayDeque implements the Deque interface, which stands for "Double-Ended Queue." When used as a stack, you only interact with one end: the top.

<<interface>> Deque<E> class ArrayDeque<E> Use as Stack push() / pop() / peek()

The Formal Declaration

// Recommended: program to the interface Deque<String> stack = new ArrayDeque<>(); stack.push("A"); // top: A stack.push("B"); // top: B, A stack.push("C"); // top: C, B, A stack.peek(); // returns "C" (no removal) stack.pop(); // returns "C", now: B, A stack.pop(); // returns "B", now: A

Stack vs Queue vs Deque

Stack (LIFO) Queue (FIFO) Deque (Both)
Add push(e) offer(e) push / offer
Remove pop() poll() pop / poll
Inspect peek() peek() peek / peekLast
Order Last-In, First-Out First-In, First-Out Either end
Java class ArrayDeque LinkedList ArrayDeque

How to Apply It

1
Import: Add import java.util.Deque; and import java.util.ArrayDeque; at the top of your file.
2
Declare: Use the interface type: Deque<Type> stack = new ArrayDeque<>();
3
Push: Call stack.push(element) to add to the top.
4
Peek: Call stack.peek() to view the top without removal. Returns null if empty.
5
Pop: Call stack.pop() to remove and return the top. Throws NoSuchElementException if empty.
6
Check empty: Use stack.isEmpty() before pop to avoid exceptions.

Example 1: Reverse a String

Push every character onto the stack, then pop them all off. Since the stack is LIFO, the characters come out in reverse order.

public static String reverse(String s) { Deque<Character> stack = new ArrayDeque<>(); for (char c : s.toCharArray()) { stack.push(c); } StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) { sb.append(stack.pop()); } return sb.toString(); }

Tracing the Reverse

Push Phase 'H' 'E' 'L' 'L' 'O' TOP pop all Pop Phase O L L E H Result: "OLLEH" "HELLO" pushed → popped in reverse

Example 2: Balanced Brackets

A classic stack problem: given a string of brackets, determine if every opening bracket has a matching closing bracket in the correct order.

public static boolean isBalanced(String s) { Deque<Character> stack = new ArrayDeque<>(); for (char c : s.toCharArray()) { if (c == '(' || c == '[' || c == '{') { stack.push(c); } else { if (stack.isEmpty()) return false; char top = stack.pop(); if (!matches(top, c)) return false; } } return stack.isEmpty(); } private static boolean matches(char open, char close) { return (open == '(' && close == ')') || (open == '[' && close == ']') || (open == '{' && close == '}'); }

Example 3: Undo History

Every action is pushed onto the stack. When the user presses Undo, pop the most recent action. Peek shows the current state.

Deque<String> history = new ArrayDeque<>(); history.push("Type 'Hello'"); history.push("Bold text"); history.push("Change font"); System.out.println(history.peek()); // "Change font" history.pop(); // Undo "Change font" System.out.println(history.peek()); // "Bold text"

Inside push()

Internal Array (circular) Before push("D"): Stack is [C, B, A] [0] [1] "C" [2] "B" [3] "A" [4] [5] head (top) After push("D"): head moves, new element inserted "D" "C" "B" "A"

pop() vs peek() on Empty

Method Non-Empty Stack Empty Stack
push(e) Adds to top Adds to top (stack now has 1 element)
pop() Returns + removes top NoSuchElementException
peek() Returns top (no removal) Returns null
isEmpty() false true
size() Number of elements 0

Common Mistakes

✕ Using Stack class
Writing Stack<E> s = new Stack<>() uses the legacy synchronized class. Use Deque instead.
✕ Declaring as ArrayDeque
Writing ArrayDeque<E> as the variable type exposes deque-specific methods. Declare as Deque<E>.
✕ Popping without checking
Calling pop() on an empty stack throws NoSuchElementException. Always check isEmpty() first.
✕ Mixing stack and queue calls
Using offer() and push() on the same Deque adds to opposite ends, breaking your logic.

Summary Cheat Sheet

Declare
Deque<E> stack = new ArrayDeque<>();
Push
stack.push(e) adds to top
Pop
stack.pop() removes + returns top (throws if empty)
Peek
stack.peek() returns top (null if empty)

Question 1 of 5

Which is the recommended way to declare a stack in modern Java?

Question 2 of 5

What does stack.pop() return when called on an empty ArrayDeque?

Question 3 of 5

What is printed to the console?

Question 4 of 5

Why is java.util.Stack considered a poor choice for implementing a stack?

Question 5 of 5

Which method should you call to check if the stack is empty before calling pop()?