[英]What is the difference between these statements in a generic class?
我還在學習泛型,並有一個問題。 假設你有這個通用類:
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>();
}
}
所有的陳述都匯編了,但我真的不知道是什么讓它們與眾不同。 任何人都可以對這三個陳述給我一個簡短的解釋。
Test t1 = new Test();
在這里,您使用的是Raw類型 。 即,不為您的generic clas
傳遞Type argument
。
編譯器應該在這里給你一個警告
測試是原始類型。 應參數化對泛型類型Test的引用
Test<String> t2 = new Test<String>();
在這里你使用泛型。 將String作為type argument
傳遞給generic class
。
Test t3 = new Test<String>();
編譯器也應該在這里給你一個警告:
- 測試是原始類型。 應參數化對泛型類型Test的引用
與第一種情況相同,但在調用構造函數時使用的是參數化類型。
還有另一個類可以在+ java 7版本中正常工作。
Test<String> t4 = new Test<>();
如果由於Type Inference使用+ java 7,則此處沒有編譯器警告
在這種情況下,由於引入了type inference
泛型類型,因此您不需要在構造函數調用期間提供泛型類型。
泛型為您提供編譯時類型檢查。
它有助於添加您可以/不能對項目執行的操作的示例(為了便於示例,我已將Test
更改為ArrayList
):
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");
它們實際上都創建了相同的對象 唯一的區別是它們在其余代碼中如何被語法處理。
t1
和t3
將以完全相同的方式處理,因為它們是相同的類型 - 它們將被視為具有類Test
的對象,僅此而已。
在類型檢查方面, t2
將得到更嚴格的處理。 如果有一些機會讓編譯器使用其通用的<String>
質量,那么也需要該質量來匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.