简体   繁体   English

Java PriorityQueue Comparator - 如何/何时排序?

[英]Java PriorityQueue Comparator - How/When do you sort?

I'm initialising a Priority Queue like: 我正在初始化一个优先级队列,如:

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

The code for my Comparator class is: 我的Comparator类的代码是:

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. 我在FuelPriority类的compare方法中设置了一个断点,但根本没有调用它。 Am I missing something here? 我在这里错过了什么吗?

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. API表示不保证PriorityQueue迭代器以任何特定顺序遍历优先级队列的元素。 It's only guaranteed that poll, remove, peek, and element access the element at the head of the queue (least element) 它只能保证轮询,删除,查看和元素访问队列头部的元素(最少元素)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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