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 - Java 中的计数和终止字符串

java - Jaxb 返回空值

java - 为什么这个 JSF 表达式不起作用?

关于捕获组的java正则表达式问题

java - 有什么方法可以使用客户端套接字连接在服务器端获取客户端的计算机名称?(例如:-Windows-PC)

java - 如何同步java事件中更新的值

Java跨语言加密

java - 如何在上述情况下使用 Java 8 Optional?

java - Selenium(JAVA) 网格仅在 Windows 中同时启动 10 个浏览器