2013-02-22 98 views
10

我仍在學習泛型,並有一個問題。假設你有這個通用類:泛型類中這些語句之間的區別是什麼?

public class Test<T> { 

    public static void main (String[] args) { 
     Test t1 = new Test(); 
     Test<String> t2 = new Test<String>(); 
     Test t3 = new Test<String>(); 
    } 
} 

所有的語句編譯,但我真的不知道是什麼使他們不同。任何人都可以給我一個關於這三個陳述的簡短解釋。

+0

幾乎如此。另外兩個只是廣告警告,但不是真正的編譯錯誤。 – 2013-02-22 11:46:39

回答

9
Test t1 = new Test(); 

在這裏,您使用的是原始類型。即,您的generic clas s沒有通過Type argument

編譯器應該給你這裏

測試警告是原始類型。引用泛型類型測試應該是 參數

Test<String> t2 = new Test<String>(); 

這裏使用的是仿製藥。將String作爲type argument傳遞給您的generic class

Test t3 = new Test<String>(); 

編譯器也應該在這裏給你一個警告過:

  • 測試是一種原始類型。引用泛型類型測試應參數

與您的第一種情況,但使用的是參數化類型,而調用構造函數。

還有另一個類在+ java 7版本中正常工作。

Test<String> t4 = new Test<>(); 

沒有編譯器警告在這裏,如果你使用+ Java的7由於類型推斷

在這種情況下,由於引進type inference泛型類型的推斷,所以你並不需要提供通用在構造函數調用期間鍵入。

+1

我們還應該補充說明,原來的問題缺少兩種組合:'Test t4 = new Test()',它不會編譯,因爲它試圖將一個原始類型的引用分配給一個泛型類型;和'Test t5 = new Test <>()',它使用Java 7中新的「鑽石算子」編譯。 – yshavit 2013-02-22 11:48:43

+1

+1和自java 7以外,你也可以編寫測試 t4 = new Test <>();這相當於T2聲明... – pgras 2013-02-22 11:49:40

+1

@yshavit和pgras只是增加了它的傢伙:) – PermGenError 2013-02-22 11:50:09

2

它們全部實際上創建了相同的對象。唯一的區別是它們在代碼的其餘部分是如何被句法處理的。

t1t3將在完全相同的方式進行處理,因爲它們是同一類型 - 它們將被視爲與Test類,沒有更多的對象。

t2將在類型檢查方面更嚴格。如果有機會讓編譯器利用其通用的<String>質量,那麼該質量也將需要匹配。

3

泛型爲您提供編譯時類型檢查。

它有助於增加你可以/不可以與你的項目做的例子(我已經改變了TestArrayList爲了便於舉例):

ArrayList t1 = new ArrayList(); 
    ArrayList<String> t2 = new ArrayList(); 
    ArrayList t3 = new ArrayList<String>(); 

    // First list can have ANYTHING added to it 
    // Compiler won't check because no generics 
    t1.add(new Integer("7")); 
    t1.add("Hello"); 

    // Second list can only have Strings added to it 
    // Compiler will check and throw compile error for anything else 
    t2.add(new Integer("7")); // doesn't compile 
    t2.add("Hello"); 

    // Third list is interesting... 
    // Again, can have ANYTHING added to it 
    // This is because generics (in Java...) are swapped out at COMPILE time 
    // rather than RUNTIME. The compiler can see that the actual type is just 
    // plain ArrayList 
    // If you like, it's similar to doing: 
    // Object o = (String) new Object(); 
    // The net-effect is everything reduced back to Object 
    t3.add(new Integer("7")); // fine 
    t3.add("Hello"); 
相關問題