I am trying to implement PriorityQueue. This PriorityQueue is going to hold instances of class Task. These instances of Task should be arranged in such a way that the instances which have higher "priority" are at the head of the Queue. In short, instances should be in descending order of priority.
private static Queue<Task> testQ = new PriorityQueue<Task>(11, new TaskQueueComparator());
/*** Comparator ***/
public class TaskQueueComparator implements Comparator<Task> {
public int compare(Task task1, Task task2) {
return task2.priority - task1.priority;
}
}
/**** Task definition **/
public class Task {
public int priority;
}
/**** Code in main() ****/
Task pe11 = new Task();
pe11.priority = 3;
testQ.add(pe11);
pe11 = new Task();
pe11.priority = 1;
testQ.add(pe11);
pe11 = new Task();
pe11.priority = 2;
testQ.add(pe11);
void displayQueue() {
int size = testQ.size();
for (int k = 0; k < size; k++)
{
Task p = testQ.poll();
System.out.format("Task Priority %d \n", p.priority); // The result I am getting is 3 1 2.. I was expecting 3 2 1
}
As shown in the comment, this outputs 3,1,2 instead of 3,2,1 like I was expecting. Can someone please let me know what mistake I am doing here ? Every time I remove or add a task from /to the queue, the queue should arrange the tasks in descending order of priority.
Let me know.
Thanks Josh