2012-10-01 57 views
1

Graph<T>类有Node<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>) 

为什么?提前致谢?

+2

什么语言?我在猜测C#,但可能有其他人使用相同(或类似)的语法。 –

+2

你在哪里定义了addVertice?我们在例子中看不到它。 –

+2

您应该使'Node'类为'static'。 – 2012-10-01 04:49:14

回答

1

你的内部类不应重写T由于T在在OuterClass已被使用。考虑如果允许会发生什么。你的外部类会提到Integer,而内部类也会提到另一个类,对于同一个实例也是如此。

​​

或者你可以使用Static Inner class因为静态泛型类型比实例泛型类型不同。

更多解释你可以参考JLS # 4.8. Raw Types

1

以下代码适合我。运行在JRE 1.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); 
    } 


} 
相关问题