为什么我们不能做 Listmylist = ArrayList();
问题描述:
为什么我们做不到
List<Parent> mylist = ArrayList<child>();
答
假设我们可以.那么这个程序应该没问题:
Suppose we could. Then this program would have to be fine:
ArrayList<Banana> bananas = new ArrayList<Banana>();
List<Fruit> fruit = bananas;
fruit.add(new Apple());
Banana banana = bananas.get(0);
这显然不是类型安全的 - 您最终在香蕉集合中得到了一个苹果.
That's clearly not type safe - you've ended up with an apple in the collection of bananas.
你可以做的是:
List<? extends Fruit> fruit = new ArrayList<Banana>();
这是安全的,因为编译器不会让您尝试将添加到水果列表中.它知道这是一个某种水果的列表,所以你可以这样写:
this is safe, because the compiler won't then let you try to add to the list of fruit. It knows that it's a list of some kind of fruit, so you could write:
Fruit firstFruit = fruit.get(0);
但它不知道它的列表具体是哪种水果,并确保您不会做错事.
but it doesn't know what exact kind of fruit it's a list of, and make sure you can't do the wrong thing.
请参阅 Java 泛型常见问题解答另一种解释.