Java PriorityQueue Comparator - How/When do you sort?

笑着哭i 提交于 2019-12-05 12:49:06

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;
    }
}

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)

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