[英]Why don't you get a compiler error when assign raw types to generic types?
我一直在看OJCPA代碼片段,我很困惑,為什么編譯器不會在以下代碼中拋出錯誤。
List l = new ArrayList();
l.add("a");
l.add("b");
l.add(1);
List<String> strList = new ArrayList<>();
strList = l; //#1 - Why does the assignment compile?
for(String s: strList) {
System.out.println(s); //#2 - It makes sense that it then throws a ClassCastException
}
我認為編譯器會將List l視為原始類型,並且因為泛型是不變的,所以它會產生編譯器錯誤,因為它不是List <String>類型。
謝謝你的幫助。
它允許向后兼容。
假設您正在調用返回String
的List
的遺留方法,但它是在將泛型添加到Java之前編寫的,因此它返回一個原始List
。
您希望此行傳遞編譯:
List<String> strList = someOldMethodThatReturnsRawList();
否則,您必須在新代碼中繼續使用原始List
類型才能調用該方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.