Stack Methods: push, pop, and peek
You'll learn how to use Deque's stack-oriented methods for LIFO (Last-In-First-Out) operations in Java.
What Are These Methods?
While Deque offers many operations for working with both ends of the collection, Java provides three convenience methods that make it feel like a traditional stack: push(), pop(), and peek(). These methods give you stack semantics without needing a separate Stack class.
How They Map to Deque Operations
These stack methods are simply aliases for Deque's first-element operations:
push(e)→ Maps toaddFirst(e)— adds an element to the front (top of stack)pop()→ Maps toremoveFirst()— removes and returns the front elementpeek()→ Maps topeekFirst()— returns the front element without removing it
Think of it like a stack of plates: you always add new plates on top (push), take plates from the top (pop), and look at the top plate without removing it (peek).
Why Use These Methods?
When you're using a Deque specifically as a stack, these methods make your code more readable and intention-revealing. Instead of addFirst() and removeFirst(), you write push() and pop(), which clearly signals LIFO behavior.
Deque<String> stack = new ArrayDeque<>();
stack.push("First"); // Adds to top
stack.push("Second"); // Adds to top
stack.push("Third"); // Adds to top
stack.peek(); // Returns "Third" (doesn't remove)
stack.pop(); // Removes and returns "Third"
stack.pop(); // Removes and returns "Second"
Key Takeaway: push(), pop(), and peek() are stack-oriented convenience methods on Deque that map to addFirst(), removeFirst(), and peekFirst(), making LIFO operations more expressive and familiar for stack use cases.