Hi Team,

Im reading Collections. It is mentioned that while intialising priority queue, it uses natural ordering by default.
But my output is not like that. Below is my code and output.

public class BackedCollections {


    public static void main(String[] args) {


        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

        pq.offer(3);
        pq.offer(1);
        pq.offer(5);
        pq.offer(2);
        pq.offer(12);
        pq.offer(14); 
        pq.offer(0);


        System.out.println(pq);


    }

}

** OUTPUT **

[0, 2, 1, 3, 12, 14, 5]

It Should be [0,1,2,3,5,12,15] right ? Please clarify

PriorityQueue inherits its toString() from java.util.AbstractCollection, which doesn't know about sort orders. (println uses toString() on all its arguments).
If you poll() the elements as intended, you get them in the correct order, eg

Integer i;
while ((i = pq.poll())!= null) System.out.print(i + " ");

Thanks James
I read Poll method will remove the highest priority from the queue. I dont want to remove any of them. So i should use peek right?

peek if you want to see the first item without removing it, yes.
I don't think gthere's any way to see the later items in the correct order without removing (poll) the first element.
NB highest priority == lowest Integer value, counter-intuitively!

oh right !! ... Understood.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.