在 Java 中,我应该使用什么来首先返回最大元素的 PriorityQueue? [英] In Java what should I use for a PriorityQueue that returns the greatest element first?

查看:33
本文介绍了在 Java 中,我应该使用什么来首先返回最大元素的 PriorityQueue?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于在 Java 中,我应该使用什么来首先返回最大元素的 PriorityQueue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆