Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • 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
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

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()+ "< ");
 
Beauty is in the eye of the tiny ad.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic