有人可以向我解释为什么标记为 //this line gives a compile error (why?)
的行吗?在下面的代码示例中不起作用?
import java.util.ArrayList;
public class GenericCastCheck {
class A{
}
class B extends A{
}
public static void main(String[] args) {
A aObject = new A();
B bObject = new B();
//this line works fine
aObject = bObject;
//this line gives a compile (expected)
bObject = aObject;
ArrayList<A> aList = new ArrayList<A>();
ArrayList<B> bList = new ArrayList<B>();
//this line gives a compile error (why?)
aList = bList;
//this line gives a compile error (expected)
bList = aList;
}
}
具体来说,当我们说 bList
类型为 ArrayList<B>
, 是不是表示它的每个元素都是B
的一个实例?如果是这样,那么将其转换为 ArrayList<A>
的问题是什么? , 如果我们可以转换 B
的个别实例至 A
?
谢谢。
最佳答案
问题是这样的:
ArrayList<A> aList = new ArrayList<A>();
ArrayList<B> bList = new ArrayList<B>();
aList = bList; // if this were valid...
aList.add(new A()); // ...what should happen here?
B b = bList.get(0); // ...and here?
如果你对数组做同样的事情,你会在运行时在第 4 行得到一个 ArrayStoreException。对于泛型集合,决定在编译时防止此类事情发生。
关于java - 为什么将 ArrayList 的泛型转换为父类(super class)不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6044329/