Reputation: 291
I am writing a prim algorithm in java. To enable a good extendibility, I used some generics. But there's a generics mismatch that bothers me a lot. I summarize it here and show my code below.
the class of LazyPrimMST is to calculate a graph's mst. So I define a generics to present the type of all kinds of WeightedGraph. In my implementation, the part of the LazyPrimMST generics is >, and there are two subclass of WeightedGraph and they are DenseWeightedGraph and SparseWeightedGraph. In my test main function, I want to calculate the mst for a DenseWeightedGraph instance, so I instantiate the generics of the part of LazyPrimMST like DenseWeightedGraph, but I get a weird error which is Bound mismatch: The type DenseWeightedGraph<Double> is not a valid substitute for the bounded parameter <Graph extends WeightedGraph<Weight>> of the type LazyPrimMST<Weight,Graph>
Error info
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Bound mismatch: The type DenseWeightedGraph<Double> is not a valid substitute for the bounded parameter <Graph extends WeightedGraph<Weight>> of the type LazyPrimMST<Weight,Graph>
related code, part of LazyPrimMST class
public class LazyPrimMST<Weight extends Number & Comparable<Weight>, Graph extends WeightedGraph<Weight>> {
private Graph G;
private MinHeap<Edge<Weight>> pq;
private boolean[] marked;
private List<Edge<Weight>> mst;
private Weight mstWeight;
public LazyPrimMST(Graph graph) {
this.G = graph;
pq = new MinHeap<>(G.E());
marked = new boolean[G.V()];
mst = new ArrayList<>();
part of my test main which contains the error line
DenseWeightedGraph<Double> g2 = new DenseWeightedGraph<>(8, false);
ReadWeightedGraph readGraph2 = new ReadWeightedGraph(g2, filename);
System.out.println("test g1 in Dense Graph:");
g2.show();
System.out.println();
LazyPrimMST<Double, DenseWeightedGraph<Double>> mst = new LazyPrimMST<>(g2); // error line
for (Edge<Double> edge: mst.mstEdges()) {
System.out.println("(" + edge + ") ");
}
part of DenseWeightedGraph
public class DenseWeightedGraph<Weight extends Number & Comparable> implements WeightedGraph {
private int n;
private int m;
private boolean directed;
private Edge<Weight>[][] g;
public DenseWeightedGraph(int n, boolean directed) {
this.n = n;
this.m = 0;
this.directed = directed;
g = new Edge[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
g[i][j] = null;
}
}
}
Upvotes: 1
Views: 51
Reputation: 503
The declaration of DenseWeightedGraph
states that it implements WeightedGraph
, not WeightedGraph<Weight>
. This ought to have caused the error.
As @Tom mentioned in the comment to your question, you have also not specified that Weight
extends Comparable<Weight>
and not just Comparable
in general. While this compiles (a backwards-compatibility feature), the use of raw types in strongly discouraged.
Upvotes: 2