实现Java Comparator [英] Implementing Java Comparator

查看:837
本文介绍了实现Java Comparator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个利用最小优先级队列的算法,所以我在google上查看并找到了PriorityQueue。看来,为了使用它,我需要告诉它我希望它如何优先排序,并且这样做的方法是使用比较器(我想比较我的Node1的特定数据字段)对象)。更多谷歌搜索提出了创建一个新的比较器的想法,该比较器实现了比较器,但覆盖了比较方法。我正在尝试的是这个(以及它的其他变体):

I am trying to write an algorithm which utilizes a min-priority queue, so I looked around on google and found the PriorityQueue. It seems that in order to use it, though, I am going to need to tell it how I want it to prioritize, and that the way to do this is with a comparator (I want to compare specific data fields of my "Node1" objects). More googling presented the idea of creating a new comparator which implements Comparator but overrides the compare method. What I am trying is this (and other variations of it as well):

import java.util.Comparator;

public class distComparator implements Comparator {

    @Override
    public int compare(Node1 x, Node1 y){
        if(x.dist<y.dist){
            return -1;
        }
        if(x.dist>y.dist){
            return 1;
        }
        return 0;
    }
}

编译器有几个理由抗议,其中一个是我没有超越比较器类(它说它是抽象的)

The compiler protests on several grounds, one of which is that I haven't over-ridden the comparator class (which it says is abstract)


错误:distComparator不是抽象的,不会覆盖比较器中的抽象方法compare(Object,Object)

error: distComparator is not abstract and does not override abstract method compare(Object,Object) in Comparator

我已将其切换为compare(object x,object y),它负责这个问题。此时虽然编译器抱怨它无法在x或y中找到dist变量 - 这是有道理的,因为它们是我的Node1类的一部分,而不是Object类。

I have switched it to say "compare(object x, object y)", which takes care of that issue. At this point though the compiler complains that it can't find the "dist" variable in x or y--which makes sense, since they are part of my Node1 class, not the Object class.

那么这应该是怎么回事?它显然应该有 Object 类型,但是如何将它指向正确的变量?

So how is this supposed to work? It should have type Object, apparently, but then how do I direct it to the correct variable?

推荐答案

您需要实现 Comparator< Node1>

public class distComparator implements Comparator<Node1> {
                                                 ^^^^^^^

如果没有这个,你正在实施 Comparator< Object> ,这不是你想要的(它可以工作,但不值得麻烦)。

Without this, you are implementing Comparator<Object>, which isn't what you want (it can be made to work, but isn't worth the hassle).

如果 Node1 有一个名为 dist 的可访问成员,那么你问题中的其余代码就可以了。

The rest of the code in your question is fine, provided Node1 has an accessible member called dist.

请注意,如果您使用的是Java 7,则该方法的整个主体可以替换为

Note that if you are using Java 7, the entire body of the method can be replaced with

return Integer.compare(x.dist, y.dist);

(用<$ c $替换整数 c> Double 等,具体取决于 Node1.dist 的类型。)

(replace Integer with Double etc, depending on the type of Node1.dist.)

这篇关于实现Java Comparator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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