gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:44:23 25 4
gpt4 key购买 nike

我有以下类(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/

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