Java PriorityQueue 比较器 - 如何/何时排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22792932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:53:57  来源:igfitidea点击:

Java PriorityQueue Comparator - How/When do you sort?

javapriority-queuecomparator

提问by Connor Cartwright

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 FuelPriorityclass, but it wasn't called at all. Am I missing something here?

运行模拟后,元素根本没有排序——它们是随机的;我在我FuelPriority班级的 compare 方法中设置了一个断点,但它根本没有被调用。我在这里错过了什么吗?

采纳答案by Alexandre Santos

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

回答by Evgeniy Dorofeev

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)

API 表示 PriorityQueue 迭代器不能保证以任何特定顺序遍历优先级队列的元素。只保证 poll、remove、peek 和 element 访问队列头部的元素(最少元素)