PriorityQueue
The PriorityQueue
class was introduced in Java 1.5
.
PriorityQueue
is an unbounded queue based on the priority heap
. Elements in the priority queue can be sorted naturally by default or provided Comparator
when the queue is instantiated. When Comparator
is not specified, it is default to a minimum
heap.
PriorityQueue
does not allow null
values and does not support non-comparable objects, such as user-defined classes. Priority queues require Java Comparable
and Comparator
interfaces to sort objects, and the elements in them are processed according to priority when sorting.
The size of the PriorityQueue
is unlimited, but you can specify an initial size when you create it. When we add elements to the priority queue, the queue size will automatically increase.
PriorityQueue
is not thread-safe, so Java provides PriorityBlockingQueue
(implements the BlockingQueue
interface) for Java multi-threaded environments.
Example:
1 | public class PriorityQueueExample { |
Output:
1 | 1 |
How PriorityQueue is implemented
Implemented through the heap, specifically a small top heap implemented through a complete binary tree (the weight of any non-leaf node is not greater than the weight of its left and right child nodes), which means that array can be used as the underlying implementation of
PriorityQueue
.
1 | /** |
The relationship between the index of parent and child nodes is as follows:
- leftNo = parentNo * 2 + 1
- rightNo = parentNo * 2 + 2
- parentNo = (nodeNo-1) / 2
The time complexity of the add(E e)
and offer(E e)
operations is log(N):
1 | public boolean add(E e) { |
The time complexity of the poll()
operation is log (N):
1 | public E poll() { |