Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Priority Queue problem

 
Shrikanth Nekkanti
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic