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

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

问题描述

Java的 PriorityQueue 地方最小的元素在列表的头部,但是我需要它来放置最大的元素在头。

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.

因为我写的类存储在这个队列中,我可以简单地反转结果 compareTo ,它不在此队列外部使用。

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.

只是一个快速的谢谢大家,Comparator听起来像我需要只要我教自己如何写一个。

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

推荐答案

传递 Comparator ,当您实例化 PriorityQueue

看起来像这样:

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天全站免登陆