有人可以向我解释这种行为:
注意:在 SomeThingGeneric 中从未使用过 T
public static class SomeThingGeneric<T> {
public List<String> getSomeList() {
return null;
}
}
final SomeThingGeneric<Object> someThingGenericObject = new SomeThingGeneric<Object>();
final SomeThingGeneric<?> someThingGenericWildcard = new SomeThingGeneric<Object>();
final SomeThingGeneric someThingGenericRaw = new SomeThingGeneric<Object>();
for (final String s : someThingGenericObject.getSomeList()) { } // 1 - compiles
for (final String s : someThingGenericWildcard.getSomeList()) { } // 2 - compiles
for (final String s : someThingGenericRaw.getSomeList()) { } // 3 - does not compile!
(1) 和 (2) 编译但 (3) 失败并显示以下消息:
incompatible types
found : java.lang.Object
required: java.lang.String
如果有人想要完整的代码,这里是. 我已经在 Java 5 和 6 中验证了这一点。