aspose file tools*
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


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Priority Queue problem" Watch "Priority Queue problem" New topic
Author

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>();
pq.add("silpa");
pq.add("swati");
pq.add("roopa");
pq.add("abc");
System.out.println(pq);
System.out.println(pq.poll());
System.out.println(pq.peak());
}
The output I got is
[abc silpa swathi roopa]
abc
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
Marshal

Joined: Mar 22, 2005
Posts: 42913
    
  68
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: http://aspose.com/file-tools
 
subject: Priority Queue problem