• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Priority Queue question

 
Ranch Hand
Posts: 220
Eclipse IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("2");
pq.add("4");
pq.add("3");
pq.add("1");
pq.add("10");
System.out.println(pq);
result is [1, 10, 3, 4, 2]

I would like to learn why 2 is at the end ?
It does not seem to be naturally ordered if 2 is at the end ?


Moreover if I used like this

PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("5");
pq.add("2");
pq.add("4");
pq.add("3");
pq.add("1");
System.out.println(pq);

the result is [1, 2, 4, 5, 3]

I am really confused why the result varies like this ?
Help needed?


and also it does not chande if I used Integer instead of String

PriorityQueue<Integer> pqn = new PriorityQueue<Integer>();
pqn.add(5);
pqn.add(2);
pqn.add(4);
pqn.add(3);
pqn.add(1);
System.out.println(pqn);
result is [1, 2, 4, 5, 3]
 
Sheriff
Posts: 9697
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 Anut!

Well this so happens because when you use an object of PriorityQue in a System.out.println(), then toString is called. PriorityQue class doesn't override the toString method. So the toString method from AbstractCollection class(a super class of PriorityQue) is called which uses an iterator on the PriorityQue object to display the elements. The documentation of the PriorityQue class says that the iterator of a priorityQue not necessarily iterate over the elements in sorted order.

So basically PriorityQue is not internally sorted. It only provides elements while polling and peeking in sorted order.

You can some more details in this Similar Question.
 
Be reasonable. You can't destroy everything. Where would you sit? How would you read a tiny ad?
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic