java - 为什么在这种情况下编译器不能限制返回类型

标签 java

我有以下类(class):

Class Container<E extends Supertype>{
    ...
    public ArrayList<E> getList(){...}
    ...
}

但是当我尝试这样做时:

public void someFunction(Container x){
    ....
    for(Supertype s : x.getList()){
        ...
    }
    ...
}

它给出一个编译错误,指出 x.getList() 的元素属于 Object。但是,既然元素必须是 E 类型,它必须是 Supertype 的子类,为什么编译器不能“解决这个问题”?

我的第一个想法是由于原始类型的问题,但那些不只是编译器不确定某些东西在运行时是否合法吗?


是的,我可以

public void someFunction(Container<?> x)

当我传递原始 Container 时,它甚至不会给出未经检查的警告。只是尝试在这里学习 Java 的怪癖。

最佳答案

是的,这是原始类型的问题。 When using a value of some raw type, any generics that are involved are erased.

The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) 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.

The erasure of a generic type whose parameters have (or don't have) a bound is the type itself.

The erasure of a parameterized type (§4.5) G<T1,...,Tn> is |G|.

以下

public ArrayList<E> getList() {...}

成为

public ArrayList getList() {...}

这使得 ArrayList#iterator()

public Iterator<E> iterator() {...}

成为

public Iterator iterator() {...}

制作Iterator#next()

public E next();

成为

public Object next();

关于java - 为什么在这种情况下编译器不能限制返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27198362/

相关文章:

java - 我可以在 Java 中用于 <index, value> 格式参数的最佳数据类型

java - 从另一个数组列表添加(连接)到 Arraylist 的元素

java - 用java创建图像

javascript - 从 Web 应用程序生成设计好的 PDF 报告

java - 需要帮助来理解可用的 JVM "Garbage Collection Algorithm"和 "Garbage Collector"

java - vscode coderunner 执行java代码有问题

java - Libgdx Android Gradle 构建错误

java - Android,当应用程序启用设备管理员时更改 GPS 状态

java - 存储一组字符串的最佳方式是什么

java - 从 jdeveloper 12c 部署项目时出错