3

I was learning Java and trying to learn priority queue in collections. I tried with below example from one website:

import java.util.*;    
class S
{
    public static void main(String args[])
    {
        PriorityQueue<String> queue=new PriorityQueue<String>();
        queue.add("Amit");
        queue.add("Vijay");
        queue.add("Karan");
        queue.add("Rahul");
        queue.add("Jai");

        System.out.println("iterating the queue elements:");
        Iterator<String> itr=queue.iterator();
        while(itr.hasNext())
        {
            System.out.println(itr.next());
        }
    }
}

here results came is below:

Amit
Jai
Karan
Vijay
Rahul`

I was expecting the result as :

Amit
Vijay
Karan
Rahul
Jai

I am not able to understand how the result changes from my expectation and what type of normal or default priority is used.
In case i want to get the same result as per my expectation, what should i do using prioiryqueue?

Please help me.

Here i want the exact cause of default ordering in priority queue.

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122

1 Answers1

2

Quoting javadoc of PriorityQueue:

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

As you can see, the ordering of the PriorityQueue doesn't matter when using iterator(). Now if you began to take values from the queue using poll(), you would get the values in lexicographical order, i.e. the natural order of String.

If you want a queue that returns items in insertion order, use a regular Queue implementation like LinkedList or ArrayDeque.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • Just one more thing..as per my question, i checked with Debug in eclipse and queue is showing the same element order what iterator is showing. I also tried to understand the lexicographic but still doesn't able to understand how this was inserted for default ordering. – Sumit Kumar Agarwal May 26 '16 at 13:17
  • @SumitKumarAgarwal For `PriorityQueue`, the *ordering* (default or otherwise) applies to `poll()` and `remove()`, not to `iterator()`. Eclipse uses `toString()` for the display and that internally uses `iterator()`. Eclipse also shows the backing array named `queue`, which is a flat representation of a balanced binary tree, which also explains the weird iteration order. – Andreas May 26 '16 at 15:15