• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Priority Queue problem

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Just let me do the talking. Ahem ... so ... you see ... we have this tiny ad...
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic