2013-09-23 35 views
1

我正在創建一個類,雙向鏈表和ListNode作爲內部類。我不能在我的代碼中實例化類Integer的對象(Java)

public class DoublyLinkedList<Integer> { 

    /** Return a representation of this list: its values, with adjacent 
    * ones separated by ", ", "[" at the beginning, and "]" at the end. <br> 
    * 
    * E.g. for the list containing 6 3 8 in that order, return "[6, 3, 8]". */ 
    public String toString() { 
     String s; 

     ListNode i = new ListNode(null, null, *new Integer(0)*); 

爲什麼我得到錯誤,無法實例化類型Integer

+0

向我們展示'ListNode'類的定義。 –

回答

7

您的類定義中的Integer是隱藏Integer包裝類的泛型類型參數。

所以,你在課堂上使用的new Integer(0)Integer作爲類型參數,而不是Integer類型本身。因爲對於類型參數T,您不能僅僅執行 - new T();,因爲該類型在該類中是通用的。編譯器不知道它是什麼類型。所以,代碼無效。

試着改變你的類:

public class DoublyLinkedList<T> { 
    public String toString() { 
     ListNode i = new ListNode(null, null, new Integer(0)); 
     return ...; 
    } 
} 

它會奏效。但我懷疑你真的想要這個。我想你想在你的泛型類中實例化類型參數。那麼,這是不可能的。

您通過實際的類型參數在實例像這樣的類:

DoublyLinkedList<Integer> dLinkedList = new DoublyLinkedList<>(); 

P.S:如果你解釋清楚你的問題的陳述,並把一些情況下進入的問題這將是更好。

+0

這個問題的最可能的答案:) +1。 –

相關問題