Reputation:
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;
}
}
Upvotes: 1
Views: 5290
Reputation: 20520
Yes: you need your Vertex
method to implement Comparable<Vertex>
.
Java's PriorityQueue
is an implementation of a heap, which has log-time insertion, and log-time removal of the minimum element. But in order for that to be meaningful, you need to have a notion of minimum; and that means you need whatever you put into a PriorityQueue
to be Comparable
, so that two elements in the heap can be compared.
The reason that non-Comparable
elements can be inserted into a PriorityQueue
is that you can also specify a Comparator
in the constructor, rather than using Comparable
elements. So as an alternative, you could leave your Vertex
class as it is, but use the appropriate constructor (which also requires you to specify an initial capacity):
PriorityQueue<Vertex> vertices = new PriorityQueue<Vertex>(11,
new Comparator<Vertex>() {
//implement .compare() and .equals()
});
Upvotes: 0
Reputation: 65793
Prims algorithm uses the weight of the edge to determine the best path. Posting the vertex to the PriorityQueue
will not work.
I am guessing your Edge
class will implement Comparable
by comparing their lengths.
Upvotes: 3
Reputation: 39437
The solution is to have your Vertex
class implement Comparable
, or to provide a Comparator
to the priority queue when constructing it. The Java collections framework needs a way to compare your vertices (after all you're putting them into a priority queue and priority implies the necessity of some ordering being present).
Upvotes: 0