简体   繁体   English

使用自定义比较器类时出错

[英]Error using custom comparator class

I am trying to implement Dijkstra's Algorithm for adjaceny matrix, and I am using Java priority Queue to do so. 我正在尝试为邻接矩阵实现Dijkstra的算法,并且正在使用Java优先级队列来做到这一点。 For my vertex I am creating a custom comparator class, but I am getting the following error: 对于我的顶点,我正在创建一个自定义比较器类,但是出现以下错误:

 <anonymous Dijkstra$1> is not abstract and does not override abstract method compare(vertex,vertex) in java.util.Comparator
        PriorityQueue<vertex> Q = new PriorityQueue<vertex>(n,new Comparator<vertex>() {        

here is the code: 这是代码:

import java.util.Scanner;
import java.io.File;
import java.util.PriorityQueue;
import java.util.Comparator;
class vertex {
    int v,d;
    public vertex(int num,int dis){
        v =num;
        d=dis;
    }
    public int getv(){
        return v;
    }
    public int getd(){
        return d;
    }
}

and then I use this to create a new priority queue: 然后使用它创建一个新的优先级队列:

PriorityQueue<vertex> Q = new PriorityQueue<vertex>(n,new Comparator<vertex>() {        
            public int compare (Object a, Object b){
            vertex v1 = (vertex)a;
            vertex v2 = (vertex)b;
            if (v1.getd() > v2.getd()){
                return +1;
            }else if (v1.getd() < v2.getd()){
                return -1;
            }else {
                return 0;
            }
        }});

the error you are getting is because you did'nt implemented the correct method. 您收到的错误是因为您未实现正确的方法。 the signature of the compare method for Comparator<vertex> is public int compare (vertex a, vertex b); Comparator<vertex>compare方法的签名是public int compare (vertex a, vertex b); and not public int compare (Object a, Object b); 而不是public int compare (Object a, Object b); .

moreover, as JB Nizer stated wisely, it would be better to implement your compare method as follows: 此外,正如JB Nizer明智地指出的那样,最好按以下方式实现您的compare方法:

public int compare (vertex a, vertex b) {
    return Integer.compare(a.getd(), b.getd());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM