我正在用Java编写基本算法。为了实现良好的可扩展性,我使用了一些泛型。但是有一个通用的不匹配让我很困扰。我在这里总结一下,并在下面显示我的代码。

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中使用原始类型。

08-08 00:53