Java Reference
In-Depth Information
import java.util.Queue;
class PriorityQueueDemo
final static int NELEM = 15;
public static void main(String[] args)
Comparator<Integer> cmp;
cmp = new Comparator<Integer>()
public int compare(Integer e1, Integer e2)
return e2-e1;
Queue<Integer> qi = new PriorityQueue<>(NELEM, cmp);
for (int i = 0; i < NELEM; i++)
qi.add((int) (Math.random()*100));
while (!qi.isEmpty())
System.out.print(qi.poll()+" ");
Listing 5-15 is similar to Listing 5-14 , but there are some differences. First, I have
declaredan NELEM constantsothatIcaneasilychangeboththepriorityqueue'sinitial
capacity andthenumberofelements insertedintothepriorityqueuebyspecifyingthe
new value in one place.
Second, Listing 5-15 declares and instantiates an anonymous class that implements
Comparator . Its compareTo() method subtracts element e2 from element e1 to
achievedescendingnumericalorder.Thecompilerhandlesthetaskofunboxing e2 and
e1 by converting e2-e1 to e2.intValue()-e1.intValue() .
Finally, Listing5-15 passesaninitialcapacityof NELEM elementsandtheinstantiated
comparator to the PriorityQueue(int initialCapacity, Comparat-
or<? super E> comparator) constructor.Thepriorityqueuewillusethiscom-
parator to order these elements.
Search WWH ::

Custom Search