PriorityQueue<Integer> queue = new PriorityQueue<Integer>(4);
queue.add(8);
queue.add(5);
queue.add(23);
queue.add(6);
System.out.println(queue);
Friends, The preceding code on Ubuntu 12.10 and Oracle Java 1.6 and Java 1.7, it is printing output as
[5, 6, 23, 8]
I believe this is wrong. This should have instead printed as [5, 6, 8, 23]
Is this a defect? or my understanding of priority queue is wrong?
In addition to it, if I change the position of adding 23 to PriorityQueue before or after, this works as expected.
The toString() method for the AbstractCollection class (which is what PriorityQueue uses) states that it:
returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]").
If you look at the docs for the PriorityQueue iterator, it states:
Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.
The priority only comes in to play when you extract items from the queue, not when you get a string representation of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With