Advertisement
Intermediate Java, Collections Framework

How does PriorityQueue work internally (as a binary heap), and what ordering does it use by default versus with a custom Comparator?

Short answer

PriorityQueue is backed by a binary heap (array-based, satisfying the heap property where each parent is less than or equal to its children for a min-heap), giving O(log n) insertion (offer()) and removal-of-minimum (poll()), with O(1) access to just the minimum element (peek())…

Save Java mock interview
Advertisement
AModel answer
PriorityQueue is backed by a binary heap (array-based, satisfying the heap property where each parent is less than or equal to its children for a min-heap), giving O(log n) insertion (offer()) and removal-of-minimum (poll()), with O(1) access to just the minimum element (peek()) without removing it -- by default it orders elements using their natural ordering (Comparable), or a custom Comparator supplied at construction for different ordering (like a max-heap by reversing the natural order), commonly used for algorithms needing repeated access to the smallest/largest remaining element, like Dijkstra's shortest path or a task scheduler prioritizing by urgency.
PriorityQueue<Integer> minHeap = new PriorityQueue<>();  // natural ordering: smallest first
minHeap.offer(5); minHeap.offer(1); minHeap.offer(3);
System.out.println(minHeap.poll());  // 1, the smallest

PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
maxHeap.offer(5); maxHeap.offer(1); maxHeap.offer(3);
System.out.println(maxHeap.poll());  // 5, the largest, due to reversed comparator
Real-world example
A task scheduling system uses a PriorityQueue<Task> with a custom Comparator ordering by urgency and deadline, always efficiently retrieving the next most urgent task to process via poll() without needing to scan and find the minimum across the entire task list manually each time.
Likely follow-ups
  • Why does PriorityQueue not guarantee full sorted order when simply iterating it (only poll() guarantees sorted retrieval order)?
  • What's the time complexity difference between PriorityQueue's offer/poll and a naive sorted list's equivalent operations?
Related topics