Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Using ArrayDeque as a Stack in Java

Learn how to use ArrayDeque as a stack in Java for LIFO operations, see practical code examples, and understand how it compares with the legacy Stack class.

~4 min readJava
#ArrayDeque#Java Collections#Stack#Deque
Illustration of a Java ArrayDeque used as a stack, showing LIFO push and pop operations.

When you need a last-in, first-out (LIFO) collection in Java, the legacy Stack class often comes to mind. The java.util.ArrayDeque class, however, is usually a better choice for stack operations. It provides the same push, pop, and peek behavior with a more flexible API and no built-in synchronization overhead.

Why ArrayDeque Is the Preferred Stack Implementation

The Stack class in Java has been around since Java 1.0. It extends Vector, so its operations carry synchronization overhead even when the collection is used from a single thread. ArrayDeque, introduced in Java 6, implements the Deque interface with a resizable-array implementation that is not synchronized. For single-threaded code, that design avoids locking and can improve performance. If you need thread safety, use a dedicated concurrent collection such as ConcurrentLinkedDeque instead of sharing an ArrayDeque without external synchronization.

ArrayDeque also offers a richer set of methods. You can use addFirst, addLast, removeFirst, removeLast, and their offer/poll equivalents. For stack behavior, use push, which adds to the head, and pop, which removes from the head. The Deque interface defines these methods, and ArrayDeque implements them efficiently.

Basic Stack Operations with ArrayDeque

Using ArrayDeque as a stack is straightforward. Here is a minimal example:

java
import java.util.ArrayDeque; import java.util.Deque; public class ArrayDequeStackExample { public static void main(String[] args) { Deque<String> stack = new ArrayDeque<>(); stack.push("first"); stack.push("second"); stack.push("third"); System.out.println(stack.peek()); // third System.out.println(stack.pop()); // third System.out.println(stack.pop()); // second System.out.println(stack.pop()); // first } }

The push method adds an element to the head of the deque, and pop removes the head. peek returns the head without removing it. These operations have amortized constant-time cost because ArrayDeque uses a resizable circular array.

You can also use addFirst and removeFirst directly, but push and pop are the idiomatic stack methods. The Deque interface also includes offerFirst and pollFirst, which are non-throwing alternatives: pollFirst returns null when the deque is empty, and offerFirst signals failure through its return value. For stack semantics, pop throws NoSuchElementException when the deque is empty, while push simply adds to the head.

ArrayDeque vs Stack: Key Differences

The table below summarizes the main differences between ArrayDeque and Stack.

FeatureArrayDequeStack (extends Vector)
SynchronizationNot synchronizedSynchronized
Null elementsNot allowedAllowed
Underlying structureResizable circular arrayResizable array (Vector)
Deque methodsFull Deque APIOnly Vector/List methods
PerformanceGenerally faster single-threadedHas synchronization overhead
Legacy statusModern replacementLegacy, retained for compat

Stack allows null elements, but ArrayDeque does not. This is a deliberate design choice: Deque implementations generally prohibit null to avoid ambiguity with methods that return null to indicate an empty deque (poll, peek). If you need to store null values, you must use a different collection or wrap the value.

Performance and Memory Behavior

ArrayDeque uses a dynamically resizing array. When the array is full, it doubles its capacity and copies the elements to a new array. This amortized cost is O(1) per operation, similar to ArrayList. Because ArrayDeque is not synchronized, removing locks can make it faster than Stack in single-threaded use, though the exact difference depends on the workload and JVM. In a multi-threaded environment, do not share an ArrayDeque without external synchronization; otherwise, you risk data corruption. For concurrent access, use ConcurrentLinkedDeque or synchronize externally.

Memory-wise, ArrayDeque stores elements in an internal array that grows on demand. It does not allocate a node object per element like LinkedList does, so its memory footprint is usually modest. If memory use is a concern for your workload, measure it in your target environment.

Handling Null Elements and Other Edge Cases

Because ArrayDeque forbids null, calling push(null) throws a NullPointerException. This is a deliberate contract of ArrayDeque. If you need to represent "no value" in a stack, consider using a sentinel object or an Optional wrapper. Another edge case is the empty stack: pop() on an empty ArrayDeque throws NoSuchElementException. If you prefer a non-throwing alternative, use pollFirst() which returns null. For example:

java
Deque<Integer> stack = new ArrayDeque<>(); Integer value = stack.pollFirst(); // returns null, no exception

This behavior is consistent with the queue-style methods on Deque and is useful when you are processing input of unknown length.

When to Use ArrayDeque and When to Use a Different Structure

ArrayDeque is the right choice when you need a LIFO stack in a single-threaded context. It is also excellent as a general-purpose deque for both stack and queue operations. If you need a FIFO queue, ArrayDeque can be used with addLast and removeFirst. However, if you require thread safety, you should use ConcurrentLinkedDeque for a lock-free deque or wrap ArrayDeque with Collections.synchronizedDeque. For random access by index, a List implementation like ArrayList is more appropriate. For frequent insertions and deletions in the middle, a LinkedList might be better, though it has higher memory overhead per element.

The decision comes down to the access pattern and concurrency requirements. ArrayDeque is a strong default choice for stack and queue operations in single-threaded code.

Iteration and Bulk Operations

ArrayDeque supports iteration in both directions. The default iterator iterates from head to tail, which is the same order as pop would remove elements. You can also use descendingIterator() to iterate from tail to head. This is useful when you need to process elements in insertion order. For example:

java
Deque<String> stack = new ArrayDeque<>(); stack.push("a"); stack.push("b"); stack.push("c"); for (String s : stack) { System.out.println(s); // c, b, a } for (String s : stack.descendingIterator()) { System.out.println(s); // a, b, c }

Bulk operations like removeIf and clear are also supported. The removeIf method lets you remove matching elements in a single pass, avoiding manual removal while iterating. This is particularly useful when you need to filter a stack based on a predicate.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.