Java - 对比较器感到困惑并且需要使用一个(我认为)。里面有更多信息
我创建了一个名为 Foo 的类。 Foo 有三个字段,它们都是整数:x、y 和 z。我想制作一个 PriorityQueue
在不同情况下以不同方式优先考虑 Foo 对象。例如,我可能想按 x 值、y 值或 z 值确定优先级。但直到运行时我才知道要优先考虑哪个值。我听说您可以使用比较器以某种方式即时施加排序,我认为这在这里是完美的。
不过,我对如何做到这一点感到困惑。如果我想使用比较器对 x 进行优先级排序(而不必重写 Foo 类中的compareTo 函数),有人可以给我举个例子吗?
非常感谢。
I created a class called Foo. Foo has three fields, which are all ints: x, y, and z. I want to make a PriorityQueue<Foo>
which prioritizes the Foo objects differently in different situations. For instance, I might want to prioritize by x value, or maybe by y value, or maybe by z. But I won't know which value I want to prioritize by until runtime. I've heard you can use comparators to somehow impose an ordering on the fly, which I think would be perfect here.
I'm confused as to exactly how I would do this though. Could someone please show me an example if say I wanted to prioritize on x using a comparator (without having to override the compareTo function in my Foo class)?
Thank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
比较器是一个参数化接口,允许您定义如何比较参数化类型的两个实例。假设您有以下类
然后要定义一个比较器,该比较器根据 x 值然后 y 然后 z 对元素进行排序,我们将执行以下操作
类似地,您可以定义首先根据 y 值然后 x 和 z 比较元素的比较器。 。ETC
最后,在运行时,您可以使用该比较器实例化 PriorityQueue
有关详细信息,请查看 优先级队列 javadoc 以及 比较器 javadoc
编辑:请参阅@buritos 关于整数溢出的评论。
A comparator is a parameterized interface that allows you to define how two instances of the parameterized type can be compared. let's assume you have the following class
Then to define a comparator that orders elements based on their x value then y then z we'd do the following
Similarly you can define comprators that compare elements based first on their y value then x the z...etc
Finally at runtime you can instantiate a PriorityQueue with that comparator
For more information take a look at the priority queue javadoc as well as the comparator javadoc
Edit: Please see @buritos comment regarding integer overflow.