PriorityQueue Example in java

PriorityQueue(Since Java 1.5) :

  • It is an unbounded priority queue based on priority heap.
  • The elements of the priority queue are ordered according to the constructor which you use.
  • PriorityQueue pq = new PriorityQueue()

It creates empty priority queue with default initial capacity 11.

Priority order is natural sorting order.

  • PriorityQueue pq = new PriorityQueue(int intialCapacity, Comparator C)

It creates empty priority queue with the specified initial capacity.

Priority order is customized sorting order.

  • The objects should be Homogenous and Comparable, if you want natural sorting order.
  • For customized sorting order, the objects need not to be Homogeneous and Comparable.
  • Insertion order is not preserved in Priority Queue.
  • Duplicate objects are not allowed in Priority Queue.
  • Null object is not allowed in Priority Queue.

Example:

 Output:

 

Explanation:

   1.     System.out.println(pq)

Prints [1, 2, 4, 5, 3]

Reason why it’s not printed in sorted order:

It invokes toString() method of AbstractCollection class, there it is using iterator in which there is no guarantee that it                  prints based on natural sorting order.

From the docs: “The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue            in any particular order.”

    2.    while (pq.size()>0)

System.out.println(pq.remove());

Prints

1

2

3

4

5

Posted in collections and tagged , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">