我正在用java编写一个prim算法。为了实现良好的可扩展性,我使用了一些泛型。但泛型不匹配让我很困扰。我在这里总结并在下面显示我的代码。
LazyPrimMST 类用于计算图的 mst。所以我定义了一个泛型来表示各种WeightedGraph的类型。在我的实现中,LazyPrimMST泛型的部分是>,并且WeightedGraph有两个子类,它们是DenseWeightedGraph和SparseWeightedGraph。在我的测试主函数中,我想计算 DenseWeightedGraph 实例的 mst,因此我实例化了 LazyPrimMST 部分的泛型,如 DenseWeightedGraph,但我收到一个奇怪的错误,即 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>
错误信息
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>
相关代码,LazyPrimMST类的一部分
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<>();
我的测试主部分包含错误行
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 + ") ");
}
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;
}
}
}
最佳答案
DenseWeightedGraph
的声明声明它实现了 WeightedGraph
,不是WeightedGraph<Weight>
。这应该导致了错误。
正如 @Tom 在对您的问题的评论中提到的,您也没有指定 Weight
延伸Comparable<Weight>
不仅仅是Comparable
一般来说。虽然此编译(向后兼容功能),但在 strongly discouraged 中使用原始类型.
关于java - 用于指定泛型的子类显示绑定(bind)不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56091410/