2012-10-01 62 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); 
    } 


} 
相關問題