是的,由于类型擦除,它可以进行转换,但它是一个坏主意™并且在执行此操作之后以正常方式使用列表的代码将抛出ClassCastException.
但这可能是因为这段代码运行:
List<Integer> l = new ArrayList<Integer>();
((List)l).add("hello");
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为通过转换为原始List类型而不是参数化List<Integer>类型,我们绕过了编译检查; 并且在运行时,类型参数信息(大部分)由于类型擦除而消失,因此字符串成功添加到列表中.
但同样,任何List<Integer>引用正常写入列表的代码(例如,根据List<Integer>合同)都会在尝试访问该条目时爆炸,因为代码将尝试转换String为Integer.
看得更深入:
List<Integer> l = new ArrayList<Integer>();
((List)l).add("hello");
System.out.println("Added successfully");
Iterator it = l.iterator(); // Old-fashioned raw iterator works
while (it.hasNext()) {
System.out.println(it.next());
}
for (Object o : l) { // Enhanced for with Object works
System.out.println(o);
}
for (Integer i : l) { // But this throws when it reaches the
System.out.println(i); // String, because String cannot be cast
} // to Integer
Run Code Online (Sandbox Code Playgroud)