作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
有人可以向我解释一下这种行为吗:
注意: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
如果有人想要完整的代码,here it is 。我已经在 Java 5 和 6 中验证了这一点。
最佳答案
嗯,尽管有人反对,但这是一个有趣的问题。我相信问题的答案就在 JLS 的这一部分中:
The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.
实际上,你的方法public List<String> getSomeList
获得有效签名public List getSomeList
,在通过原始类型访问它的场景中。因此,结果列表的列表迭代器将“返回”对象而不是字符串。
关于Java 泛型类型推断奇怪的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15895711/
我是一名优秀的程序员,十分优秀!