我不确定为什么以下代码中的最后一条语句是非法的。 Integer
应该是 的子类型?
,为什么我不能将它分配给 b
?
List<String> a = new ArrayList<String>();
a.add("foo");
// b is a List of anything
List<?> b = a;
// retrieve the first element
Object c = b.get(0);
// This is legal, because we can guarantee
// that the return type "?" is a subtype of Object
// Add an Integer to b.
b.add(new Integer (1));
最佳答案
重点是 b
引用了 some 类型的列表,但是编译器不知道类型是什么,所以它不会 知道向其添加Integer
是否有效。还有一件好事,给定您的示例 - 您将向最初创建的对象添加一个 Integer
以保存字符串列表。当然,在 Java 中,该信息在执行时会丢失 - 但编译器会尽力确保您的安全。
参见 Java generics FAQ获取更多信息。
关于java - 了解 Java 泛型中的通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8481052/