Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

implementation - Implementing Java Comparator

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)

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to implement Comparator<Node1>:

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

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).

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...