小编Nik*_*las的帖子

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

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

在本课程中Foo<T>,该strings成员与T以下内容无关:

package test;
import java.util.ArrayList;

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

    T getSome() {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

该类用于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
    }
}
Run Code Online (Sandbox Code Playgroud)

编译错误是"不兼容的类型.必需:String found:Object".

似乎Java 在使用raw类型时忘记了Stringtype参数.ArrayListFoo

我的java版本是1.7.0_21

java generics

9
推荐指数
1
解决办法
912
查看次数

标签 统计

generics ×1

java ×1