Stacks with ArrayDeque
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A stack is a collection where the last value added is the first one taken out: last in, first out, or LIFO. In Java you build one with ArrayDeque and its push, pop and peek methods.
Last in, first out
A stack is a collection where values are added and removed at the same end, called the top, so the last value added is the first one removed. This rule is called last in, first out (LIFO).
A stack follows one rule: last in, first out. Think of a pile of parcels on the packing desk of an online store. A packed parcel goes on top, and the courier takes the parcel from the top. The parcel put down last is picked up first. The end you work with is called the top.
This order is exactly what many programs need. The Undo button cancels your most recent change first. The phone's Back button returns to the screen you saw most recently. When you read brackets like {[(, the bracket opened last must be closed first.
Java itself uses a stack for method calls: each call is placed on top, and it is removed when the method returns. Endless recursion fills this stack, which is the StackOverflowError you may have seen.
A stack with ArrayDeque
push puts a value on top of a stack, and pop removes and returns the top value. peek looks at the top value without removing it. pop on an empty stack throws NoSuchElementException.
Declare it with the Deque interface: Deque<String> stack = new ArrayDeque<>();. A deque (say "deck") can add and remove at both ends; a stack simply uses one end, the front, as its top.
Example 1 · push, pop and peek
import java.util.ArrayDeque;import java.util.Deque;
public class StackBasicsDemo { public static void main(String[] args) { Deque<String> parcels = new ArrayDeque<>(); parcels.push("Parcel 1"); parcels.push("Parcel 2"); parcels.push("Parcel 3"); System.out.println("Pile (top first): " + parcels); System.out.println("On top: " + parcels.peek());
System.out.println("Taken: " + parcels.pop()); System.out.println("Taken: " + parcels.pop()); parcels.push("Parcel 4"); System.out.println("Pile now: " + parcels + ", size " + parcels.size()); }}Pile (top first): [Parcel 3, Parcel 2, Parcel 1] On top: Parcel 3 Taken: Parcel 3 Taken: Parcel 2 Pile now: [Parcel 4, Parcel 1], size 2
What this code does
- Parcel 3 was pushed last, so it is on top:
peekshows it and the firstpoptakes it. - Compare with a queue: the same three values in a queue would come out as Parcel 1 first.
Example 2 · Undo history in a notes app
import java.util.ArrayDeque;import java.util.Deque;
public class UndoDemo { static String text = ""; static Deque<String> history = new ArrayDeque<>();
static void type(String words) { history.push(text); text = text + words; System.out.println("Typed -> \"" + text + "\""); }
static void undo() { if (history.isEmpty()) { System.out.println("Nothing to undo"); return; } text = history.pop(); System.out.println("Undo -> \"" + text + "\""); }
public static void main(String[] args) { type("Buy pens"); type(", files"); type(", stapler"); undo(); undo(); type(", tape"); undo(); undo(); undo(); }}Typed -> "Buy pens" Typed -> "Buy pens, files" Typed -> "Buy pens, files, stapler" Undo -> "Buy pens, files" Undo -> "Buy pens" Typed -> "Buy pens, tape" Undo -> "Buy pens" Undo -> "" Nothing to undo
What this code does
- Before every change, the old text is pushed. Undo pops the most recent old text and puts it back, so changes are undone newest first.
- The
isEmpty()check turns an extra Undo press into a friendly message instead of aNoSuchElementException.
Example 3 · Mistake: pop on an empty stack
import java.util.ArrayDeque;import java.util.Deque;
public class EmptyPopDemo { public static void main(String[] args) { Deque<String> screens = new ArrayDeque<>(); screens.push("Home"); screens.push("Cart"); System.out.println("Back to: " + screens.pop()); System.out.println("Back to: " + screens.pop()); System.out.println("Back to: " + screens.pop()); }}Back to: Cart Back to: Home Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.ArrayDeque.removeFirst(ArrayDeque.java:362) at java.base/java.util.ArrayDeque.pop(ArrayDeque.java:593) at EmptyPopDemo.main(EmptyPopDemo.java:11)
What this code does
- The third
pop()finds an empty stack. On a deque,popis the same asremoveFirst, which is why the trace names it. - Fix: check
screens.isEmpty()first, or usepoll(), which returnsnullon an empty deque instead of throwing.
push(x): putxon top.pop(): remove and return the top value; throwsNoSuchElementExceptionif the stack is empty.peek(): return the top value without removing it; returnsnullif empty.isEmpty()andsize()as usual. Printing or for-each shows the top first. All of these are O(1).
Order of execution
Which order do the values come out?
Put the printed lines in the order the program prints them.
isEmpty() before pop() whenever an empty stack is possible, for example when the user presses Undo with nothing to undo.Why not the Stack class?
Java also has an old class called Stack, from Java 1.0. Its own documentation recommends Deque instead. The example below shows the surprise it causes.
Example 4 · Why the old Stack class is risky
import java.util.ArrayDeque;import java.util.Deque;import java.util.Stack;
public class OldStackDemo { public static void main(String[] args) { Stack<String> old = new Stack<>(); Deque<String> modern = new ArrayDeque<>(); for (String s : new String[] { "a", "b", "c" }) { old.push(s); modern.push(s); } System.out.println("Stack prints: " + old); System.out.println("ArrayDeque prints: " + modern); System.out.println("Both pop: " + old.pop() + " and " + modern.pop());
old.add(0, "sneaky"); old.remove(1); System.out.println("Stack after list tricks: " + old); }}Stack prints: [a, b, c] ArrayDeque prints: [c, b, a] Both pop: c and c Stack after list tricks: [sneaky, b]
What this code does
- Both pop
c, so the LIFO behaviour is the same, butStackprints from the bottom andArrayDequefrom the top. Stackinherits list methods, so code can insert at the bottom and delete from the middle. ADequeused withpush/pop/peekkeeps the stack honest.
First, Stack extends Vector, so it also has list methods like get(0), add(0, x) and remove(2). Any code can reach into the middle and break the last-in-first-out rule. Second, every method takes a lock meant for programs that run several tasks at once, which costs time in normal programs. Third, it prints and loops from the bottom up, the opposite of ArrayDeque, which confuses readers.
You will still meet Stack in old code and in some textbooks. Read it, but write new code with ArrayDeque.
The balanced-brackets idea
Checking brackets like {[()]} is the classic stack problem. Every closing bracket must match the most recent unclosed opening bracket, and "most recent" is what a stack's top gives you.
- Read the text one character at a time.
- Opening bracket
(,[or{: push it. - Closing bracket: if the stack is empty, it is unbalanced. Otherwise pop and check that the pair matches.
- Other characters: ignore them.
- At the end, the text is balanced only if the stack is empty.
Example 5 · Balanced brackets checker
import java.util.ArrayDeque;import java.util.Deque;
public class BracketsDemo { static boolean isBalanced(String text) { Deque<Character> open = new ArrayDeque<>(); for (char c : text.toCharArray()) { if (c == '(' || c == '[' || c == '{') { open.push(c); } else if (c == ')' || c == ']' || c == '}') { if (open.isEmpty()) { return false; } char top = open.pop(); boolean pair = (top == '(' && c == ')') || (top == '[' && c == ']') || (top == '{' && c == '}'); if (!pair) { return false; } } } return open.isEmpty(); }
public static void main(String[] args) { String[] tests = { "{[()]}", "if (a[i] > 0) { x++; }", "([)]", "((", "a(b)c]" }; for (String t : tests) { System.out.println(t + " -> " + (isBalanced(t) ? "balanced" : "NOT balanced")); } }}{[()]} -> balanced
if (a[i] > 0) { x++; } -> balanced
([)] -> NOT balanced
(( -> NOT balanced
a(b)c] -> NOT balancedWhat this code does
- In
([)], the)arrives while[is on top, so the pair check fails. In((, nothing goes wrong during the loop, but two brackets are still open at the end. - In
a(b)c], the]comes when the stack is already empty: a closing bracket with no opener. Characters that are not brackets are skipped.
Next step
Check your understanding
12 quick questions