I'm trying to implement prim's algorithm, using a priority queue. When I call offer() method, it gives me a class cast exception, saying that vertex cannot be cast to comparable. Is there a workaround?
public static Collection<Edge> prims(Graph g, int start) {
ArrayList<Edge> mst = new ArrayList<Edge>();
PriorityQueue<Vertex> vertices = new PriorityQueue<Vertex>();
Vertex startVertex;
for (Vertex vertex : g.getVertices()) {
vertices.offer(vertex);
if (vertex.getId() == start) {
startVertex = vertex;
}
}
if (!mst.isEmpty()) {
return mst;
}
return null;
}
}
Prims algorithm uses the weight of the edge to determine the best path. Posting the vertex to the
PriorityQueuewill not work.I am guessing your
Edgeclass will implementComparableby comparing their lengths.