簡體   English   中英

使用自定義比較器類時出錯

[英]Error using custom comparator class

我正在嘗試為鄰接矩陣實現Dijkstra的算法,並且正在使用Java優先級隊列來做到這一點。 對於我的頂點,我正在創建一個自定義比較器類,但是出現以下錯誤:

 <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>() {        

這是代碼:

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

然后使用它創建一個新的優先級隊列:

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

您收到的錯誤是因為您未實現正確的方法。 Comparator<vertex>compare方法的簽名是public int compare (vertex a, vertex b); 而不是public int compare (Object a, Object b);

此外,正如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