Java PriorityQueue Comparator - How/When do you sort?

泪湿孤枕 提交于 2019-12-07 09:18:30

问题


I'm initialising a Priority Queue like:

strategy = new FuelPriority();
incoming = new PriorityQueue<Vehicle>(1, strategy);

The code for my Comparator class is:

public class FuelPriority implements Comparator<Object> {

public int compare(Object o1, Object o2) {

    Vehicle a1 = (Vehicle) o1;
    Vehicle a2 = (Vheicle) o2;

    return Integer.compare(a1.getFuelLevel(), a2.getFuelLevel());
  }
}

After running a simulation, the elements aren't ordered at all - they are random; I set a breakpoint in the compare method of my FuelPriority class, but it wasn't called at all. Am I missing something here?


回答1:


Aside from the typo on your code, it works for me.

import java.util.Comparator;
import java.util.PriorityQueue;

public class StackOverflow
{
    public static void main(String[] args)
    {

        FuelPriority strategy = new FuelPriority();
        PriorityQueue<Vehicle> incoming = new PriorityQueue<Vehicle>(4, strategy);
        incoming.add(new Vehicle("car1", 10));
        incoming.add(new Vehicle("car2", 20));
        incoming.add(new Vehicle("car3", 15));
        incoming.add(new Vehicle("car4", 1));

        // to retrieve the elements in order
        while (!incoming.isEmpty()) {
            System.out.println(incoming.poll());
        }

    }

}

class FuelPriority
    implements Comparator<Object>
{

    public int compare(Object o1, Object o2)
    {

        Vehicle a1 = (Vehicle)o1;
        Vehicle a2 = (Vehicle)o2;

        return Integer.compare(a1.getFuelLevel(), a2.getFuelLevel());
    }
}

class Vehicle
{

    private String name;
    private int fuelLevel;

    public Vehicle(String name, int fuelLevel)
    {
        this.name = name;
        this.fuelLevel = fuelLevel;
    }
    public int getFuelLevel()
    {
        return fuelLevel;
    }

    @Override
    public String toString()
    {
        return name + "=" + fuelLevel;
    }
}



回答2:


API says that PriorityQueue iterator is not guaranteed to traverse the elements of the priority queue in any particular order. It's only guaranteed that poll, remove, peek, and element access the element at the head of the queue (least element)



来源:https://stackoverflow.com/questions/22792932/java-priorityqueue-comparator-how-when-do-you-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!