1. List<Car> carList = new ArrayList<Sedan>();
2. List<Car> carList = new ArrayList<Car>();
carList.add(new Sedan());
1 有编译器错误,2 是合法的。
为什么变量声明的类型必须与我们传递给对象类型的类型匹配(不允许派生类型)? 我使用的数组如下,绝对正确:
int SIZE = 10;
Car[] carArray = new Sedan[SIZE];
谁能告诉我为什么集合必须声明为条件 2?谢谢
最佳答案
Sedan[]
是 Car[]
的子类型。但这对类型安全有非常负面的影响,因为下面的代码因此是合法的:
Sedan[] sedans = new Sedan[10];
Car[] cars = sedans; // legal, since Sedan[] extends Car[]
cars[0] = new Car(); // Houston, we have a problem
此代码在运行时导致 ArrayStoreException,因为本应仅包含轿车的数组实际上包含非轿车。
泛型的目标是拥有类型安全的集合。因此决定设计它们,以便在编译时而不是运行时检测到上述问题。集合比数组使用得更多,并且让它们类型安全是一件好事。
所以他们决定 List<Sedan>
不会是List<Car>
.
关于java - 数组声明和集合声明有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23547584/