Java Reference
In-Depth Information
import java.util.PriorityQueue;
import java.util.Queue;
class PriorityQueueDemo
{
public static void main(String[] args)
{
Queue<Integer> qi = new PriorityQueue<>();
for (int i = 0; i < 15; i++)
qi.add((int) (Math.random()*100));
while (!qi.isEmpty())
System.out.print(qi.poll()+" ");
System.out.println();
}
}
Aftercreatingapriorityqueue,themainthreadadds15randomlygeneratedintegers
(ranging from 0 through 99) to this queue. It then enters a while loop that repeatedly
pollsthepriorityqueueforthenextelementandoutputsthatelementuntilthequeueis
empty.
Whenyourunthisapplication,itoutputsalineof15integersinascendingnumerical
order from left to right. For example, I observed the following output from one run:
11 21 29 35 40 53 66 70 72 75 80 83 87 88 89
Because poll() returnsnullwhentherearenomoreelements,Icouldhavecoded
this loop as follows:
Integer i;
while ((i = qi.poll()) != null)
System.out.print(i+" ");
Supposeyouwanttoreversetheorderofthepreviousapplication'soutputsothatthe
largest element appears on the left and the smallest element appears on the right. As
Listing5-15 demonstrates,youcanachievethistaskbypassingacomparatortotheap-
propriate PriorityQueue constructor.
Listing 5-15. Using a comparator with a priority queue
import java.util.Comparator;
import java.util.PriorityQueue;
 
Search WWH ::




Custom Search