我使用PriorityQueue实现了Dijkstra的算法。但是在运行代码时,我得到以下异常:
Exception in thread "main" java.lang.ClassCastException: Dijkstra$Vertex cannot be cast to java.lang.Comparable
at java.util.PriorityQueue.siftUpComparable(Unknown Source)
at java.util.PriorityQueue.siftUp(Unknown Source)
at java.util.PriorityQueue.offer(Unknown Source)
at java.util.PriorityQueue.add(Unknown Source)
at Dijkstra.dijkstra(Dijkstra.java:55)
at Dijkstra.main(Dijkstra.java:89)
使用的代码是:
import java.util.HashSet;
import java.util.PriorityQueue;
public class Dijkstra {
static class Vertex{
private int vertexid;
private Double distance;
public Vertex(int vertexid, Double distance) {
this.vertexid = vertexid;
this.distance = distance;
}
public int getVertexid() {
return vertexid;
}
public Double getDistance() {
return distance;
}
public int compareTo(Vertex other) {
return this.getDistance().compareTo(other.getDistance());
}
public boolean equals(Object o) {
if (o instanceof Vertex) {
Vertex v = (Vertex) o;
return vertexid == v.vertexid && distance == v.distance;
}
return false;
}
}
public static void dijkstra(double g[][], int n, int m, int source) {
// g is the adjacency matrix
// n is the number of nodes
// m is the number of edges
// initialize shortest path
double d[] = new double[n];
d[source] = 0;
for (int i = 0; i < n; i++) {
d[i] = Double.POSITIVE_INFINITY;
}
HashSet<Integer> s = new HashSet<Integer>();
PriorityQueue<Vertex> q = new PriorityQueue<Vertex>();
// initialize q
for (int i = 0; i < n; i++) {
q.add(new Vertex(i, d[i]));
}
Vertex u;
while (!q.isEmpty()) {
u = q.remove();
System.out.println(u.getVertexid() + "\t" + u.getDistance());
s.add(u.getVertexid());
for (int i = 0; i < n; i++) {
if (i != u.getVertexid() && g[u.getVertexid()][i] != Double.POSITIVE_INFINITY) {
if (u.getDistance().doubleValue() + g[u.getVertexid()][i] < d[i]) {
q.remove(new Vertex(i, d[i]));
d[i] = u.getDistance().doubleValue() + g[u.getVertexid()][i];
q.add(new Vertex(i, d[i]));
}
}
}
}
}
public static void main(String[] args) {
double graph[][] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};
Dijkstra.dijkstra(graph, 8, 14, 0);
}
}
Vertex类用于创建基本上存储顶点及其标签距离的结构。优先级队列将对此类的对象起作用,并将使用距离值作为删除操作的排序值。如何纠正异常?
答案 0 :(得分:0)
请改为尝试:
static class Vertex implements Comparable<Vertex> {