ArrayDeque
ArrayDeque is a resizable ring buffer that works as a queue or a stack. Adds and removes at both ends are amortized O(1). It forbids null.
Detailed Explanation
A deque is a double-ended queue. You can push and pop at the head and the tail. ArrayDeque stores elements in an array and keeps head and tail indexes. When an index walks off the end, it wraps. When the array fills, it doubles. There are no per-element nodes, so it beats LinkedList for queues and stacks on both time and memory.
As a queue: offerLast / pollFirst (or offer / poll). As a stack: push / pop at the head. The Stack class is a synchronized subclass of Vector and is leftover. The JDK documentation tells you to use ArrayDeque instead.
null is rejected because the implementation uses null slots to mean empty. get by index is not part of the Deque interface; the class is not a List. If you need random access, use ArrayList. Iteration is from head to tail in FIFO order.
You reach for ArrayDeque as the default Queue and the default stack. You reach for LinkedList only if you need null elements or List methods. You reach for ArrayBlockingQueue or ConcurrentLinkedDeque when threads share the structure. You reach for PriorityQueue when the next element is the smallest, not the oldest.
The cost of ArrayDeque is wrapping-index arithmetic you do not see, and a resize copy when it grows. Pre-size if you know the peak. The cost of using Stack or Vector is a lock on every call. The cost of using LinkedList as a queue is node allocation and cache misses.
removeFirstOccurrence and contains are O(n). Ends are O(1). It is not thread-safe.
Code Examples
import java.util.ArrayDeque;
import java.util.Deque;
public class QueueDemo {
public static void main(String[] args) {
Deque<String> q = new ArrayDeque<>();
q.offerLast("a");
q.offerLast("b");
q.offerLast("c");
System.out.println(q.pollFirst()); // prints: a
System.out.println(q.peekFirst()); // prints: b
}
}import java.util.ArrayDeque;
import java.util.Deque;
public class StackDemo {
public static void main(String[] args) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop()); // prints: 3
System.out.println(stack.pop()); // prints: 2
}
}Common Gotchas
`null` is forbidden
`offer(null)` throws `NullPointerException`.
`Stack` is not the type to use
it is synchronized `Vector`. Use `ArrayDeque`.
Not a `List`
there is no cheap `get(i)`. Copy to a list if you need indexes.
Not thread-safe
use a blocking or concurrent deque for shared work.