Java › Collections Framework
What is the purpose of the Deque interface, and how does it unify both stack (LIFO) and queue (FIFO) behavior in a single interface?
IntermediateAnswer
Deque (double-ended queue) supports insertion and removal at both ends (addFirst/addLast, removeFirst/removeLast, and their peek equivalents), letting a single interface serve as both a stack (using push()/pop(), which operate on the front) and a FIFO queue (using offer()/poll(), which operate on opposite ends) -- ArrayDeque is the generally recommended, more efficient modern replacement for both the legacy Stack class (which is a poorly-designed, unnecessarily synchronized holdover from Java 1.0) and LinkedList when used purely as a queue/stack, due to better performance characteristics and no unnecessary synchronization overhead.
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1); stack.push(2); stack.push(3);
System.out.println(stack.pop()); // 3, LIFO stack behavior
Deque<Integer> queue = new ArrayDeque<>();
queue.offer(1); queue.offer(2); queue.offer(3);
System.out.println(queue.poll()); // 1, FIFO queue behaviorReal-world example A modern codebase replaces legacy usage of java.util.Stack with ArrayDeque (used via push()/pop()), following the widely-cited JDK documentation recommendation, gaining better performance and avoiding Stack's unnecessary built-in synchronization overhead that's irrelevant for typical single-threaded stack usage.