在 Java 中,我应该使用什么来首先返回最大元素的 PriorityQueue?

2022-01-25 00:00:00 compare java compareto

Java 的 PriorityQueue 位置列表头部的最小元素,但是我需要它将最大的元素放在头部.获得具有这种行为的优先级队列的最佳方法是什么.

由于我编写了存储在这个队列中的类,我可以简单地反转 compareTo 的结果,它没有在这个队列之外使用.

不过,我喜欢让代码准确地表示我正在建模的内容,我想要做的是先获得最大的,所以代码应该这样说,而不是最不寻常的定义最不重要.

解决方案

传一个Comparator 在您实例化 PriorityQueue.

看起来像这样:

公共类 ReverseYourObjComparator 实现 Comparator{公共 int 比较(最终 YourObj arg0,最终 YourObj arg1){返回 0 - arg0.compareTo(arg1);}}

Java's PriorityQueue places the least element at the head of the list, however I need it to place the greatest element at the head. What what's the neatest way to get a priority queue that behaves like that.

Since I wrote the class stored in this queue I could simply reverse the results of compareTo, its not used outside this queue.

However I like to make the code an accurate representation of what I'm modeling, what I'm trying to do is get the greatest first so the code should say that rather than least first with an unusual definition of least.

[edit]just a quick thank you everyone, Comparator sounds like what I need just as soon as I teach myself how to write one.

解决方案

Pass a Comparator that inverts the natural order when you instantiate the PriorityQueue.

It would look something like this:

public class ReverseYourObjComparator implements Comparator<YourObj> {
    public int compare(final YourObj arg0, final YourObj arg1) {
        return 0 - arg0.compareTo(arg1);
    }
}

相关文章