The elements of the priority queue are ordered according to their natural ordering, or by a
provided at queue construction time, depending on which constructor is used. PriorityQueue is declared as follows:
class PriorityQueue< 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
, the methods defined by
interface must be implemented:
The following example demonstrates these methods:
public static void main(String arg)
PriorityQueue<Integer> num = new PriorityQueue<Integer>(); // LINE A
//num.offer(null); LINE B
for (int i = 0; i < 3; i++)
In this example, a
PriorityQueue is declared which is of type
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
LINE B in the above program to see java.lang.NullPointerException since priority queue does not permit null elements.