0

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

2
Contributors
4
Replies
12
Views
3 Years
Discussion Span
Last Post by murali2489
Featured Replies
  • 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 + " "); Read More

  • 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! Read More

1

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 + " ");

Edited by JamesCherrill

0

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?

1

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!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.