Java:在泛型类中使用类型变量

ahb*_*ore 4 java generics compilation

有人可以向我解释为什么这段代码不能编译?

即使它使用泛型类而不提供特定类型T,它应该能够在编译时识别ArrayList保存字符串.

public class Test {
    public static void main(String[] args){
        Container container = new Container();
        container.strings.add("test");
        String s1 = container.strings.get(0); // does not compile
        ArrayList<String> local = container.strings;
        String s2 = local.get(0); // does compile
    }

    static class Container <T>{
        ArrayList<String> strings = new ArrayList<String>();
    }
}
Run Code Online (Sandbox Code Playgroud)

Boh*_*ian 7

当您使用泛型类作为原始类型(未指定类型的类型)时,将从类中剥离所有通用信息(是否使用省略的类型).

因此当您编码Container container(而不是Container<SomeClass> container)ArrayList<String> strings成为时ArrayList strings,就像使用它一样ArrayList<Object>.

要"修复",请指定类型Container(即使您不使用该类型):

Container<Object> container = new Container<Object>();
Run Code Online (Sandbox Code Playgroud)

其余的将现在编译.


这样做的原因是向后兼容早期的Java前通用版本(1.4及更早版本)

  • @ K-ballo:因为Java泛型作为事后的想法粘在上面,在运行时,所有东西都是"对象".泛型只在编译时才真正做到了. (2认同)