Queue and Deque
Queue is a collection designed for holding elements before processing, usually FIFO. Deque is a queue that lets you add and remove at both ends. Both are interfaces; ArrayDeque is the common implementation.
Detailed Explanation
A list is for access by position. A queue is for "the next thing to do". Queue methods come in two families. add/remove/element throw when the operation is not possible (full bounded queue, empty queue). offer/poll/peek return false or null instead. Use the second family when emptiness is a normal case, and the first when emptiness is a bug.
Deque extends Queue. It adds addFirst, addLast, offerFirst, offerLast, removeFirst, removeLast, pollFirst, pollLast, peekFirst, peekLast, plus push/pop as stack names for the head. A Deque used only at one end is a stack. Used as offerLast/pollFirst it is a FIFO queue.
Implementations split by need. ArrayDeque: general-purpose, unbounded, not thread-safe, no nulls. LinkedList: list plus deque, allows nulls, slower. PriorityQueue: ordered by priority, not FIFO. ArrayBlockingQueue, LinkedBlockingQueue, ConcurrentLinkedQueue: concurrent and/or blocking. LinkedBlockingDeque is a concurrent deque.
You reach for Queue in the type of a field when callers should only produce and consume, not index. You reach for Deque when you need both ends (BFS vs adding to the front for 0-1 BFS, undo stacks plus queues). You do not use Queue as a list; get(i) is not there.
The cost of picking the throw-vs-return family wrongly is an unexpected NoSuchElementException on an empty poll you meant to handle, or a swallowed null you meant to treat as a bug. Remember poll returns null for empty, so a queue that allowed null elements would be ambiguous; most queue implementations forbid null for that reason.
Java 21 sequenced collections add SequencedCollection methods that overlap some deque operations. Prefer the interface that matches the access pattern you want to allow.
Code Examples
import java.util.ArrayDeque;
import java.util.Queue;
public class Work {
public static void main(String[] args) {
Queue<String> jobs = new ArrayDeque<>();
jobs.offer("scan");
jobs.offer("pack");
while (!jobs.isEmpty()) {
System.out.println(jobs.poll());
}
// prints:
// scan
// pack
System.out.println(jobs.poll()); // prints: null
}
}import java.util.ArrayDeque;
import java.util.Deque;
public class BothEnds {
public static void main(String[] args) {
Deque<Integer> d = new ArrayDeque<>();
d.addLast(2);
d.addFirst(1);
d.addLast(3);
System.out.println(d); // prints: [1, 2, 3]
System.out.println(d.removeLast()); // prints: 3
}
}Common Gotchas
`remove()` on an empty queue throws
`poll()` returns `null`. Pick the family that matches "empty is normal" vs "empty is a bug".
`PriorityQueue` is a `Queue` but not FIFO
do not assume arrival order.
Most queues reject `null`
`offer(null)` throws.