What Is a PriorityQueue?
You'll learn what a PriorityQueue is and how it differs from regular queues by ordering elements by priority instead of insertion order.
The Core Idea
Unlike a regular queue (like LinkedList as Queue) that follows strict FIFO order — first in, first out — a PriorityQueue orders elements based on their priority. When you poll from a PriorityQueue, you don't get the element that was added first; you get the element with the highest priority (or lowest value, by default).
Think of it like an emergency room: patients aren't treated in the order they arrived, but by the severity of their condition. The most urgent case gets attention first, regardless of when they walked in.
How Priority Is Determined
The PriorityQueue uses either:
- The elements' natural ordering (if they implement
Comparable) - A custom Comparator you provide
By default, smaller values have higher priority. So with integers, 1 would be retrieved before 10, even if 10 was added first.
Why Use PriorityQueue?
PriorityQueues are essential for:
- Task scheduling where important tasks must run before less important ones
- Algorithm implementations like Dijkstra's shortest path or Huffman coding
- Event simulation where events must be processed by timestamp rather than insertion order
- Handling requests where some users or operations have higher priority
Key Difference from LinkedList Queue
With LinkedList as Queue, insertion order is the retrieval order. With PriorityQueue, priority determines retrieval order — insertion order is completely ignored.
Key Takeaway: A PriorityQueue retrieves elements based on priority (determined by natural ordering or a Comparator) rather than insertion order, making it ideal for scheduling and priority-based processing tasks.