1

クラスにNode<T>(内部)クラスがありGraph<T>ます:

public class Graph<T> {
    private ArrayList<Node<T>> vertices;
    public boolean addVertex(Node<T> n) {
        this.vertices.add(n);
        return true;
    }
    private class Node<T> {...}
}

これを実行すると:

Graph<Integer> g = new Graph<Integer>();
Node<Integer> n0 = new Node<>(0);
g.addVertex(n0);

最後の行は私にエラーを与えます:

The method addVertice(Graph<Integer>.Node<Integer>) in the type Graph<Integer> is not applicable for the arguments (Graph<T>.Node<Integer>)

なんで?前もって感謝します?

4

2 に答える 2

1

次のコードは私にとってはうまくいきます。JRE1.6で実行

public class Generic<T> {
    private ArrayList<Node<T>> vertices = new ArrayList<Node<T>>();

    public boolean addVertice(Node<T> n) {
        this.vertices.add(n);
        System.out.println("added");
        return true;
    }


    public static class Node<T> {
    }

    public static void main(String[] args) {
        Generic<Integer> g = new Generic<Integer>();
        Node<Integer> n0 = new Node<Integer>();
        g.addVertice(n0);
    }


}
于 2012-10-01T04:55:53.650 に答える
1

内部クラスは、外部クラスですでに使用されているため、Tオーバーライドしないでください。T許可された場合に何が起こるかを考えてください。外部クラスは参照しInteger、内部クラスは同じインスタンスに対しても同じ別のクラスを参照します。

 public boolean addEdge(Node node1, Node node2) {
        return false;
    }

    Graph<Integer> g = new Graph<Integer>();
    Graph<Integer>.Node n0 = g.new Node(0);// As T happens to be integer you can use inside node class also.

    public class Node {
        T t;
        Node(T t) {
        }
    }

Static Inner classまたは、静的ジェネリック型はインスタンス型ジェネリック型とは異なるため、を使用できます。

詳細については、JLS#4.8を参照してください。生のタイプ

于 2012-10-01T04:56:24.937 に答える