gpt4 book ai didi

java - 原始类型成员的通用类型丢失

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:57:46 25 4
gpt4 key购买 nike

我在使用泛型时发现了一个奇怪的行为。

在本类(class)中 Foo<T> , strings成员(member)与T无关:

package test;
import java.util.ArrayList;

public class Foo<T> {
ArrayList<String> strings;

T getSome() {
return null;
}
}

该类在main中使用:

package test;

public class Main {

public static void main() {
Foo<Integer> intFoo = new Foo<>();
Integer i = intFoo.getSome();
String s1 = intFoo.strings.get(0);

Foo rawFoo = new Foo();
Object o = rawFoo.getSome();
String s2 = rawFoo.strings.get(0); // Compilation error on this line
}
}

编译错误是“incompatible types.required: String found: Object”。

Java 似乎忘记了 String ArrayList 的类型参数当原始类型为 Foo被使用。

我的java版本是1.7.0_21

最佳答案

简单地说,因为rawFoo是原始的,它的非静态成员也变成了原始的。

这在 JLS §4.8 中有概述。 :

More precisely, a raw type is defined to be one of:

  • The reference type that is formed by taking the name of a generic type declaration without an accompanying type argument list.

  • An array type whose element type is a raw type.

  • A non-static member type of a raw type R that is not inherited from a superclass or superinterface of R.

注意最后一个项目符号。

关于java - 原始类型成员的通用类型丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30803060/

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