gpt4 book ai didi

Java 泛型类型推断奇怪的行为?

转载 作者:行者123 更新时间:2023-12-01 22:40:43 26 4
gpt4 key购买 nike

有人可以向我解释一下这种行为吗:

注意: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 。我已经在 J​​ava 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com