I am trying to implement Dijkstra's Algorithm for adjaceny matrix, and I am using Java priority Queue to do so. 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);
and not public int compare (Object a, Object b);
.
moreover, as JB Nizer stated wisely, it would be better to implement your compare method as follows:
public int compare (vertex a, vertex b) {
return Integer.compare(a.getd(), b.getd());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.