Collections Framework

Queues, Deques & Priority Queues

Queue offers FIFO with polite failure modes; Deque adds both ends (and replaces the legacy Stack); PriorityQueue always surrenders the smallest element. ArrayDeque is the right default for both stack and queue.
  • Two method families: throwing (add/remove/element) vs value-returning (offer/poll/peek)
  • ArrayDeque: circular array, faster than LinkedList as a queue and than Stack as a stack
  • PriorityQueue: binary heap; poll is O(log n); iteration is not sorted
  • Blocking variants (ArrayBlockingQueue, LinkedBlockingQueue) live in Concurrent Collections
Stack and queue via Deque
Deque<Task> queue = new ArrayDeque<>();
queue.offer(task);            // enqueue at tail
Task next = queue.poll();     // dequeue from head (null if empty)

Deque<Frame> stack = new ArrayDeque<>();
stack.push(frame);            // addFirst
Frame top = stack.pop();      // removeFirst (throws if empty)
PriorityQueue
Queue<Job> jobs = new PriorityQueue<>(Comparator.comparing(Job::deadline));
jobs.addAll(pending);
while (!jobs.isEmpty()) {
    process(jobs.poll());     // always the earliest deadline
}
Sources
  • Core Java, Volume I: Fundamentals (13th ed.)Ch. 9.3.4–9.3.5 — Queues, Deques, Priority Queues
  • Learning Java (6th ed.)Ch. 7 — Collections