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