A special type of queue where elements are processed based on their priority rather than their insertion order. Implements a priority heap data structure where elements are ordered according to their natural ordering or a custom comparator.
Used in:
- Task scheduling by priority
- Event handling systems
- Dijkstra’s shortest path algorithm
- Huffman coding compression
- Network traffic prioritization
Key characteristics
Section titled “Key characteristics”- Elements are stored in a priority heap - a complete binary tree
- The head (first element) is always the smallest element based on natural ordering
- When elements are removed, the next smallest element becomes the head
- Elements must be comparable (implement Comparable) or use a Comparator
- Does not allow null elements
- Not thread-safe (use PriorityBlockingQueue for concurrent access)
Basic Example:
PriorityQueue<Integer> pQueue = new PriorityQueue<>();
// Adding elementspQueue.add(10);pQueue.add(5);pQueue.add(15);
// Will print in order: 5, 10, 15while(!pQueue.isEmpty()) { System.out.println(pQueue.poll());}Common Methods
Section titled “Common Methods”add(E element)- Inserts elementoffer(E element)- Adds element (preferred method)peek()- Returns but does not remove head elementpoll()- Returns and removes head elementremove(Object obj)- Removes specific elementclear()- Removes all elementssize()- Returns number of elements
Difference Between add and offer
Section titled “Difference Between add and offer”Both add and offer methods are used to insert elements into the priority queue.
-
add(E element):- Throws an
IllegalStateExceptionif the queue has a fixed capacity and is full. - Suitable for cases where you are certain the queue can accommodate the new element.
- Throws an
-
offer(E element):- Returns
trueif the element was successfully added, orfalseif the queue is full (in case of a bounded queue). - Preferred for scenarios where you want to handle capacity constraints gracefully without exceptions.
- Returns
Example
Section titled “Example”// Custom comparator for reverse orderPriorityQueue<Integer> pQueue = new PriorityQueue<>((a, b) -> b - a);
pQueue.offer(10);pQueue.offer(5);pQueue.offer(15);
// Will print in order: 15, 10, 5while(!pQueue.isEmpty()) { System.out.println(pQueue.poll());}Complexity
Section titled “Complexity”| Operation | Time | Space |
|---|---|---|
| Insertion | ||
| Removal | ||
| Peek | ||
| Contains | ||
| Size |