Consider the following program:
import java.util.*; class Task implements Comparable<Task> { int priority; public Task(int val) { priority = val; }/* w w w .ja va 2 s . c o m*/ public int compareTo(Task that) { if(this.priority == that.priority) return 0; else if (this.priority > that.priority) return -1; else return 1; } public String toString() { return new Integer(priority).toString(); } } class Main { public static void main(String []args) { PriorityQueue<Task> tasks = new PriorityQueue<Task>(); tasks.add(new Task(10)); tasks.add(new Task(15)); tasks.add(new Task(5)); Task task; while ( (task = tasks.poll()) != null) { System.out.print(task + " "); } } }
When executed, this program prints the following:
d)
The Task class implements Comparable<Task>, which specifies how to compare its elements.
The PriorityQueue method prioritizes the elements in the queue by calling the compareTo()
method.
The compareTo()
method returns -1 if the priority of the current Task object is greater than the priority of the compared Task object.
Hence the elements of the PriorityQueue are retrieved in the descending order.