Help coderanch get a
new server
by contributing to the fundraiser
  • 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

Natural ordering in PriorityQueue

 
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Folks,

I have a doubt about when exactly does 'natural ordering' take place in a PriorityQueue. Have a look at the following code:


Result:

[arrow, pink, ball]
arrow
[ball, pink]




My question is when I printed pq, the result I get is not ordered, however printing pq after invoking the poll method seems to give me an ordered result of the remaining two elements. This seem to imply that ordering took place
only after the poll method was invoked. However, if I were to replace the poll method with a peek and than print pq, the result I get is the same as the first print statement: [arrow, pink, ball] and not [arrow, ball, pink] as I was expecting after observing what happened after the poll() method. Why this difference? does ordering take place only after poll() gets invoked? Hope someone can explain. Thank you.
 
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi John, this is a very common question people have. PriorityQueue doesn't guarantee any order when you are iterating or calling toString. You can see other discussions like these: 1, 2, 3...
 
What are you doing? You are supposed to be reading this tiny ad!
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic