Java 中的类型兼容性问题

Type compatibility issues in Java

我正在尝试在 java 中实现 Kruskal 的最小生成树算法。我正在努力解决类型不兼容问题。在整个程序中,我有几个 for 循环,如下所示:

for (Edge f : G.edges()) {
            int x = f.either(), y = f.other(x);
            if (!uf.connected(x, y)) {
                if (f.weight() < e.weight()) {
                    System.err.println("Edge " + f + " violates cut optimality conditions");
                    return false;
                }
            }
        }

我看到的所有 for 循环都与此类似,其中一个 for 都具有

Edge f : G.edges()

Edge e : G.edges()

括号内。在这种情况下,Edge 是项目 Edge.java 中的另一个 class,edges 是此 class:

中的一个方法
for (Edge e : edges()) {

        // all edges in MST except e
        uf = new UF(G.V());
        for (Edge f : mst) {
            int x = f.either(), y = f.other(x);
            if (f != e) uf.union(x, y);
        }

将此代码放入 NetBeans 时,包含 for 循环的行会产生类型错误,"incompatible types: com.sun.javafx.geom.Edge cannot be converted to kruskal.Edge"NetBeans 建议通过将我的 f 和 e 变量的类型更改为边缘来解决此问题。这样做会使我的代码看起来像这样:

for (com.sun.javafx.geom.Edge e : G.edges()) {
        int v = e.either(), w = e.other(v);
        if (!uf.connected(v, w)) {
            System.err.println("Not a spanning forest");
            return false;
        }
    }

此解决方案的唯一问题是,当我实施它时,它无法识别我的 Edge.java 文件中实施的 either() 和 other() 方法。这是我的 other() 方法的示例:

public int other(int vertex) {
    if      (vertex == v) return w;
    else if (vertex == w) return v;
    else throw new IllegalArgumentException("Illegal endpoint");
}

我相信有一个我无法想到的解决这个问题的简单方法。在仍然能够从 Edge 访问我的方法的同时解决我的类型问题的最佳方法是什么 class?

问题是您引用了错误的边 class。

for (com.sun.javafx.geom.Edge e : G.edges()) {
    int v = e.either(), w = e.other(v);
    if (!uf.connected(v, w)) {
        System.err.println("Not a spanning forest");
        return false;
    }
}

应该是这样的:

for (com.your.project.model.Edge e : G.edges()) {
    int v = e.either(), w = e.other(v);
    if (!uf.connected(v, w)) {
        System.err.println("Not a spanning forest");
        return false;
    }
}

或者正确导入 class。检查您当前的导入并确保您没有显式导入 Sun 的 Edge

删除所有 "com.sun.javafx.geom.Edge"

并且在导入语句中仅使用 kruskal.Edge