• 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

Problem with Priority Queue in Java 5

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

Why does the below method does not give any output. No errors not output:
class TestPriorityQueue {

public static void main(String[] args) {
PriorityQueue<String> pq = new PriorityQueue<String>();
String[] sa = {"Left","Right","Up","Down","ne"," ", "Hurray"};

for(String s:sa){
pq.offer(s);
}
for(String s:sa){

System.out.println(pq.peek()+ " ");

}

================

But when I replace the bold line with :
System.out.println(pq.poll()+ " ");

I get what is expected. But peek should return the element but not delete it. It is doing nothing here.

Please help

Thanks
Raghu.
 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
peek() does exactly what its supposed too, it returns the head element of the queue without removing it. Remember that the Queue is a sorted data structure by default. If you do not specify a sort order then the elements of the queue are sorted according to their natural order, in this case the order in which String objects are sorted. The element, " ", is the head of the queue and your program prints that, you just don't see it.
 
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
change your println() to this and you will see if that " " shows up!

System.out.println(">" + pq.peek()+ "< ");
 
Today you are you, that is turer than true. There is no one alive who is youer than you! - Seuss. Tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic