了解Java泛型中的通配符 [英] Understanding wildcards in Java generics
问题描述
我不确定为什么以下代码中的最后一条语句是非法的。 Integer
应该是?
的子类型,为什么我不能将它分配给 b ?
I'm not sure why the last statement in the following code is illegal. Integer
should be a subtype of ?
, so why can't I assign it to 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
指的是 类型的列表,但编译器不知道类型是什么,所以它不知道是否是向它添加 Integer
是有效的。还有一件好事,就是你的例子 - 你将为最初创建的对象添加一个 Integer
来保存一个字符串列表。当然,Java在执行时会丢失这些信息,但编译器会尽可能保持安全。
The point is that b
refers to a list of some type, but the compiler doesn't know what the type is, so it doesn't know whether or not it's valid to add an Integer
to it. And a good thing too, given your example - you'd be adding an Integer
to an object initially created to hold a list of strings. Sure, that information is lost at execution time in Java - but the compiler tries to keep you as safe as it can.
请参阅有关 lot 的Java泛型常见问题解答 更多信息。
See the Java generics FAQ for a lot more information.
这篇关于了解Java泛型中的通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!