Menu
Topics Index
...
`

PriorityQueueDemo - Java Example Program


PriorityQueueDemo
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();
        }
    
    }
}
OUTPUT

1
2
5

DESCRIPTION

In 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
  • At LINE A replace the code with the below code.
    PriorityQueue<Integer> num = new PriorityQueue<>(1, new Comparator<Integer>()
    {

        public int compare(Integer i, Integer j)
        {
            return j - i;
        }
    });
    The above code changes the natural ordering of the PriorityQueue to descending order so the output will be
    5
    2
    1
  • Uncomment LINE B in the above program to see java.lang.NullPointerException since priority queue does not permit null elements.

© meritcampus 2019

All Rights Reserved.

Open In App