简体   繁体   中英

Java PriorityQueue

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

FYI, PriorityQueue only returns the elements in priority order when you poll() the Queue. I found this one out the hard way when I tired iterating over it a long time ago. Additionally, it only performs the compare on insertion. So if your priority changes while in the queue you are going to get very odd behavior.

By changing your code to the following:

void displayQueue() {
    while (!testQ.isEmpty())
    {   
    Task p = testQ.poll(); // poll, you want to remove the head
    System.out.format("Task Priority %d \n", p.priority);
    }
}

I was able to get:

Task Priority 3

Task Priority 2

Task Priority 1

At first I thought your Comparator might not be doing the right thing with "ProcessElements" but it looks like that was a typo.

This returns "3 3 3" for me, as is..

Did you mean to .poll() and not peek()?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM