The elements of the priority queue are ordered according to their natural ordering, or by a
Comparator
provided at queue construction time, depending on which constructor is used. PriorityQueue is declared as follows:
class PriorityQueue< E >
where
E
specifies the type of the object that is stored in a queue.
PriorityQueue has six constructors which are defined below:
If no comparator is specified, then the default comparator will order the type of data in the queue in ascending order. By providing a custom comparator, you can specify a different ordering scheme. The comparator() method is declared as follows:
Comparator< ? super E > comparator()
To add or remove elements to the
PriorityQueue
, the methods defined by
Queue
interface must be implemented:
The following example demonstrates these methods:
import java.util.*;
class PriorityQueueDemo
{
public static void main(String arg[])
{
PriorityQueue<Integer> num = new PriorityQueue<Integer>(); // LINE A
num.offer(1);
num.offer(5);
num.offer(2);
//num.offer(null); LINE B
for (int i = 0; i < 3; i++)
{
System.out.println(num.peek());
num.remove();
}
}
}
DESCRIPTIONIn this example, a PriorityQueue
is declared which is of type Integer
.The offer()
adds elements to the PriorityQueue
. Since no comparator is specified,the default comparator is invoked which stores the elements in ascending order. So the elements are stored in this order: 1, 2, 5. The peek()
returns the element at the head of the queue without removing the element. The remove()
removes the element at the head of the queue.
THINGS TO TRY
- Uncomment
LINE B
in the above program to see java.lang.NullPointerException since priority queue does not permit null elements.