Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Java in General and the fly likes Priority Queue problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Priority Queue problem" Watch "Priority Queue problem" New topic

Priority Queue problem

Shrikanth Nekkanti
Ranch Hand

Joined: Jul 12, 2007
Posts: 48
Hi Everybody.

Can anyone tell me in which order elements of priority queue are sorted.
I have used following code
class Test{
PriorityQueue <strings> pq=new PriorityQueue <Strings>();
The output I got is
[abc silpa swathi roopa]

Can anybody explain why the collection elements are not sorted ?
I am getting correct output with peek() n poll().According that methods i should get
[abc roopa silpa swathi ]

Explain the reason?
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
From the javadocs of AbstractCollection.toString:
The string representation consists of a list of the collection's elements in the order they are returned by its iterator

From the javadocs of PriorityQueue.iterator:
The iterator does not return the elements in any particular order.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
As you said, retrieving all entries with Queue methods gives you the order you expect.

That note about iterator was interesting. I guess they're trying hard to not reveal what their internal storage is like. And toString() in your original print of the queue is inherited from AbstractCollection which doesn't promise order, so no surprise it didn't print in order.
[ November 22, 2007: Message edited by: Stan James ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: Priority Queue problem
It's not a secret anymore!