Java Queues and Deques: ArrayDeque, LinkedList and PriorityQueue
Learn Java's Queue, Deque and PriorityQueue: offer/poll/peek versus add/remove/element, ArrayDeque as a fast queue and stack, Java 21 sequenced methods, and how a binary heap gives a priority queue O(log n) add and remove, with job scheduling and top-k examples.
kvi5hnuCode Sprout team member10 min readOn this page
A queue lets you add elements at the tail and remove them from the head efficiently. That is first in, first out: the order of a checkout line, a print spool or a breadth-first search. A double-ended queue, or deque (pronounced "deck"), lets you add and remove at both ends, so it can serve as a queue and as a stack. A priority queue always hands out the most important element next, whatever order the elements arrived in. This article covers all three, plus the data structure that makes priority queues fast: the binary heap.
The Queue interface: two flavours of every operation
Queue offers each of its three operations in two versions. They differ only in what happens when the operation can't succeed:
| Operation | Throws an exception | Returns a special value |
|---|---|---|
| insert at the tail | add(e): IllegalStateException if full | offer(e): returns false if full |
| remove the head | remove(): NoSuchElementException if empty | poll(): returns null if empty |
| inspect the head | element(): NoSuchElementException if empty | peek(): returns null if empty |
The general-purpose queues in java.util are unbounded, so add and offer always succeed there. "Full" only matters for bounded queues, such as ArrayBlockingQueue from java.util.concurrent, which the concurrency part of this course uses for producer–consumer designs.
Which flavour should you use? Use offer, poll and peek when an empty or full queue is a normal situation that your code checks for. Use add, remove and element when it would be a bug, so a failure throws an exception right away. And because null is the "empty" signal, never put null into a queue. ArrayDeque and PriorityQueue reject it outright.
Deques: both ends
The Deque interface extends Queue with operations at both ends. ArrayDeque and LinkedList both implement it, and both grow as needed.

- Insert:
offerFirstandofferLastreturnfalseif full.addFirstandaddLastthrow. - Remove:
pollFirstandpollLastreturnnullif empty.removeFirstandremoveLastthrow. - Inspect:
peekFirstandpeekLastreturnnullif empty.getFirstandgetLastthrow. - Stack methods:
push,popandpeekall work at the head.
You can't insert into or remove from the middle of a deque. Use a list if you need that.
ArrayDeque: the queue and stack you should use
ArrayDeque stores its elements in a circular array. Head and tail indexes wrap around the end of the array, so adding or removing at either end never shifts anything. Each operation is amortized O(1), there is no per-element node object, and the elements sit next to each other in memory. The result is that ArrayDeque is faster than LinkedList as a queue and faster than the legacy Stack class as a stack. Stack extends Vector, so it synchronizes every call, and it even exposes get(i) and add(i, e), which a stack shouldn't have.
Deque<Character> stack = new ArrayDeque<>(); // instead of new Stack<>()
Queue<Task> queue = new ArrayDeque<>(); // instead of new LinkedList<>()
The default constructor starts with room for 16 elements. You can pass an initial capacity if you know you'll need more. Two limitations remain: ArrayDeque rejects null elements, and it is not thread-safe.
Priority queues
A priority queue returns elements in sorted order no matter what order they were inserted in. Every call to remove or poll yields the smallest remaining element. Unlike a TreeSet, though, a priority queue does not keep everything sorted. Iterating over it, or printing it, shows the elements in a seemingly arbitrary order. Only removal is guaranteed to be ordered.
Like a tree set, a priority queue either holds Comparable elements or uses a Comparator passed to its constructor. A typical use is job scheduling. Jobs arrive in any order, and whenever a worker is free, the most urgent job is taken. By convention priority 1 is the most urgent, which fits nicely with "remove yields the minimum".
var jobs = new PriorityQueue<Job>(
Comparator.comparingInt(Job::priority).thenComparing(Job::name));
Inside: the binary heap
The data structure behind PriorityQueue is a binary heap. It is a binary tree in which every parent is less than or equal to its children. The smallest element is therefore always at the root, but siblings have no particular order, so the tree as a whole is not sorted. That is exactly why it is cheaper than a sorted structure.

The tree is complete (filled level by level), so it fits in a plain array with no links. The children of index i are at 2i + 1 and 2i + 2. That is why printing a priority queue shows this level-order array rather than a sorted list.
addputs the new element at the end of the array, then sifts it up, swapping it with its parent while it is smaller. That takes O(log n) swaps at most.remove/polltakes the root, moves the last element into the root's place, then sifts it down, swapping it with its smaller child until the order holds again. That is also O(log n).peekjust reads the root: O(1).remove(Object)andcontainsmust search the array, so they are O(n).- Building a priority queue from an existing collection with
new PriorityQueue<>(collection)takes O(n). That is faster than adding the elements one at a time.
Common patterns
- Max-heap. Pass
Comparator.reverseOrder(), or a reversed comparator, to get the largest element first. - Top k of a stream. Keep a min-heap of size k. Add each element, and whenever the size exceeds k,
pollthe smallest. At the end, the heap holds the k largest elements. The cost is O(n log k) time and O(k) memory, which is far better than sorting everything when n is huge. - Merging sorted sources, Dijkstra's shortest paths, event simulation. All of these repeatedly need "the next smallest", which is exactly what a heap provides.
A complete example
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
public class Solution {
record Job(String name, int priority) {}
public static void main(String[] args) {
// 1. Queue: FIFO with two flavours of each operation
Queue<String> line = new ArrayDeque<>();
line.offer("Ana");
line.offer("Ben");
line.add("Cy");
System.out.println("queue " + line + ", peek " + line.peek() + ", poll " + line.poll() + " -> " + line);
line.clear();
System.out.println("empty: poll " + line.poll() + ", peek " + line.peek());
try {
line.remove();
} catch (NoSuchElementException e) {
System.out.println("empty: remove() throws NoSuchElementException");
}
// 2. a bounded queue: offer returns false, add throws
Queue<Integer> bounded = new ArrayBlockingQueue<>(2);
System.out.println("offer 1: " + bounded.offer(1) + ", offer 2: " + bounded.offer(2) + ", offer 3: " + bounded.offer(3));
try {
bounded.add(3);
} catch (IllegalStateException e) {
System.out.println("add 3: IllegalStateException");
}
// 3. Deque: both ends
Deque<Integer> deque = new ArrayDeque<>();
deque.offerLast(2);
deque.offerLast(3);
deque.offerFirst(1);
deque.addLast(4);
System.out.println("deque " + deque + ", peekFirst " + deque.peekFirst() + ", peekLast " + deque.peekLast()
+ ", reversed " + deque.reversed());
System.out.println("pollFirst " + deque.pollFirst() + ", pollLast " + deque.pollLast() + " -> " + deque);
// 4. ArrayDeque as a stack: checking balanced brackets
for (String expr : List.of("{[()()]}", "([)]", "((")) System.out.println(expr + " balanced? " + balanced(expr));
// 5. PriorityQueue: removal in priority order, iteration is not sorted
var pq = new PriorityQueue<LocalDate>();
pq.add(LocalDate.of(1969, 7, 20)); // Moon landing
pq.add(LocalDate.of(1957, 10, 4)); // Sputnik
pq.add(LocalDate.of(1961, 4, 12)); // first human in space
pq.add(LocalDate.of(1903, 12, 17)); // first powered flight
pq.add(LocalDate.of(1927, 5, 21)); // first solo transatlantic flight
System.out.println("iterating: " + pq);
var removed = new ArrayList<LocalDate>();
while (!pq.isEmpty()) removed.add(pq.remove());
System.out.println("removing: " + removed);
// 6. job scheduling with a comparator: priority 1 runs first, ties by name
var jobs = new PriorityQueue<Job>(Comparator.comparingInt(Job::priority).thenComparing(Job::name));
jobs.add(new Job("backup", 3));
jobs.add(new Job("deploy", 1));
jobs.add(new Job("email", 2));
jobs.add(new Job("alert", 1));
var order = new StringJoiner(" ");
while (!jobs.isEmpty()) order.add(jobs.poll().name());
System.out.println("job order: " + order);
// 7. top k largest with a size-bounded min-heap
int[] data = {42, 7, 91, 15, 63, 88, 3, 70, 29, 55};
int k = 3;
var heap = new PriorityQueue<Integer>(); // smallest of the current top k at the head
for (int x : data) {
heap.offer(x);
if (heap.size() > k) heap.poll(); // evict the smallest
}
var top = new ArrayList<>(heap);
top.sort(Comparator.reverseOrder());
System.out.println("top " + k + ": " + top);
// 8. a max-heap
var maxHeap = new PriorityQueue<Integer>(Comparator.reverseOrder());
for (int x : data) maxHeap.add(x);
System.out.println("max-heap head " + maxHeap.peek());
}
static boolean balanced(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
switch (c) {
case '(', '[', '{' -> stack.push(c);
case ')', ']', '}' -> {
if (stack.isEmpty()) return false;
char open = stack.pop();
if ("([{".indexOf(open) != ")]}".indexOf(c)) return false;
}
default -> { }
}
}
return stack.isEmpty();
}
}
queue [Ana, Ben, Cy], peek Ana, poll Ana -> [Ben, Cy]
empty: poll null, peek null
empty: remove() throws NoSuchElementException
offer 1: true, offer 2: true, offer 3: false
add 3: IllegalStateException
deque [1, 2, 3, 4], peekFirst 1, peekLast 4, reversed [4, 3, 2, 1]
pollFirst 1, pollLast 4 -> [2, 3]
{[()()]} balanced? true
([)] balanced? false
(( balanced? false
iterating: [1903-12-17, 1927-05-21, 1961-04-12, 1969-07-20, 1957-10-04]
removing: [1903-12-17, 1927-05-21, 1957-10-04, 1961-04-12, 1969-07-20]
job order: alert deploy email backup
top 3: [91, 88, 70]
max-heap head 91
Look at the two priority queue lines. The iterating line is the heap's internal array, in which 1969 comes before 1957. The removing line is properly sorted. The bracket checker is the classic use of a stack: push every opening bracket, and when a closing bracket arrives, pop and check that it matches.
Choosing a queue
| Need | Use |
|---|---|
| FIFO queue or LIFO stack, single thread | ArrayDeque |
queue that must also be a List, or must hold null | LinkedList |
| always take the smallest (or largest) element | PriorityQueue |
| producer/consumer between threads, possibly bounded | ArrayBlockingQueue, LinkedBlockingQueue (Part 10) |
| concurrent priority queue or delayed tasks | PriorityBlockingQueue, DelayQueue (Part 10) |
Common questions
Should I use Stack for a stack?
No. Stack extends the legacy, synchronized Vector, and it allows access by index, which breaks the stack abstraction. Use Deque<E> stack = new ArrayDeque<>() with push, pop and peek.
Why is my PriorityQueue not sorted when I print it?
A priority queue is a binary heap. It only guarantees that the smallest element is at the head. Its iterator and toString show the internal array. To get the elements in order, call poll repeatedly, or copy them into a list and sort it.
How do I make a max-heap?
Pass a reversed comparator to the constructor: new PriorityQueue<>(Comparator.reverseOrder()), or Comparator.comparing(Task::priority).reversed().
What is the difference between offer and add, or poll and remove?
They do the same work but report failure differently. offer, poll and peek return false or null. add, remove and element throw an exception. With the unbounded queues in java.util, offer and add always succeed.
Which queue should I use between threads?
None of ArrayDeque, LinkedList or PriorityQueue is thread-safe. Use a BlockingQueue such as ArrayBlockingQueue, LinkedBlockingQueue or PriorityBlockingQueue, or ConcurrentLinkedQueue for non-blocking access. The concurrency part of the course covers them.
API reference
java.util.Queue<E>
| Method | Description |
|---|---|
boolean add(E e), boolean offer(E e) | insert at the tail; if the queue is full, add throws IllegalStateException and offer returns false |
E remove(), E poll() | remove and return the head; if empty, remove throws NoSuchElementException and poll returns null |
E element(), E peek() | return the head without removing it; if empty, element throws and peek returns null |
java.util.SequencedCollection<E> (Java 21)
| Method | Description |
|---|---|
void addFirst(E e), void addLast(E e) | insert at either end; throws UnsupportedOperationException if the collection can't place elements by position (sorted sets, unmodifiable collections). Deque implementations throw IllegalStateException if a bounded deque is full |
E removeFirst(), E removeLast() | remove and return an end element; throws NoSuchElementException if empty |
E getFirst(), E getLast() | return an end element; throws NoSuchElementException if empty |
SequencedCollection<E> reversed() | reverse-order view |
java.util.Deque<E>
| Method | Description |
|---|---|
boolean offerFirst(E e), boolean offerLast(E e) | insert at either end; returns false if full |
E pollFirst(), E pollLast() | remove and return an end element, or null if empty |
E peekFirst(), E peekLast() | return an end element without removing it, or null if empty |
void push(E e), E pop() | stack operations at the head (same as addFirst, removeFirst) |
Iterator<E> descendingIterator() | iterate from tail to head |
java.util.ArrayDeque<E>
| Method | Description |
|---|---|
ArrayDeque(), ArrayDeque(int initialCapacity) | unbounded deque with an initial capacity of 16 or the given value |
java.util.PriorityQueue<E>
| Method | Description |
|---|---|
PriorityQueue(), PriorityQueue(int initialCapacity) | priority queue for Comparable elements |
PriorityQueue(Comparator<? super E> c), PriorityQueue(int initialCapacity, Comparator<? super E> c) | priority queue ordered by the comparator |
PriorityQueue(Collection<? extends E> c) | priority queue built from the collection in O(n) |
Summary
Queueoffers insert, remove and inspect in a throwing version (add,remove,element) and a special-value version (offer,poll,peek).Dequeworks at both ends and doubles as a stack.ArrayDeque, a circular array, is the best general-purpose queue and stack, and it replacesStackand, for queues,LinkedList.- Since Java 21, the end-element methods live in
SequencedCollection, so lists have them too. PriorityQueueis a binary min-heap.addandpollare O(log n), andpeekis O(1). Removal order is sorted, but iteration order is not.- Use a comparator for custom priorities or a max-heap, and a size-k min-heap for top-k problems.
Practice Questions
When would you call offer instead of add on a queue?
When a full queue is an expected condition that you want to handle without exceptions, typically with a bounded queue. offer returns false instead of throwing IllegalStateException. For unbounded queues like ArrayDeque, the two behave the same.
Why should you not store null in a queue, even one that allows it, like LinkedList?
poll and peek return null to signal an empty queue. A stored null would be indistinguishable from "no element".
You print a PriorityQueue<Integer> containing 5, 1, 4 and see [1, 5, 4]. Is the queue broken?
No. toString iterates over the heap's internal array, which is only heap-ordered (parent ≤ children), not sorted. Polling repeatedly still yields 1, 4, 5.
How do you find the 10 largest values in a stream of a billion numbers without storing them all?
Keep a PriorityQueue<Integer> min-heap. For each number, offer it, and if the size exceeds 10, poll the smallest. Memory stays at 10 elements, and each step costs O(log 10).
What replaced java.util.Stack, and why?
ArrayDeque, used through the Deque methods push, pop and peek. Stack extends Vector, so every call is synchronized, and it inherits list operations like add(int, E) that break the stack abstraction.
Previous: Java HashSet and TreeSet: Hash Tables, Hash Codes and Sorted Sets
Related reading
- Java HashSet and TreeSet: Hash Tables, Hash Codes and Sorted Sets
- Java LinkedList vs ArrayList: Linked Lists, ListIterator and Array Lists
- Java Collection Interfaces: List, Set, Queue, Map and Sequenced Collections
- The Java Collections Framework: Interfaces, Implementations and Iterators
- Java ArrayList: Generic Array Lists Explained

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.