为什么我们不能做List< Parent> mylist = ArrayList< child>(); [英] Why we can't do List<Parent> mylist = ArrayList<child>();

查看:97
本文介绍了为什么我们不能做List< Parent> mylist = ArrayList< child>();的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们不能做

 列表< Parent> mylist = ArrayList< child>(); 


解决方案

然后,这个程序必须很好:

  ArrayList< Banana> bananas = new ArrayList< Banana>(); 
List< Fruit>水果=香蕉;
fruit.add(new Apple());

香蕉蕉= bananas.get(0);

这显然不是类型安全 - 你结束了一个苹果在香蕉的集合。 / p>

您可以做的是:

  List< ;? extends Fruit> fruit = new ArrayList< Banana>(); 

这是安全的,因为编译器不会让你尝试 add 到水果列表。它知道它是一个某种水果的列表,所以你可以写:

 水果firstFruit = fruit.get(0); 

但它不知道什么确切的水果它是一个列表,不要做错事。



请参阅 Java泛型常见问题另一种解释。


Why we can't do

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.

What you can do is:

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.

See the Java generics FAQ another explanation.

这篇关于为什么我们不能做List&lt; Parent&gt; mylist = ArrayList&lt; child&gt;();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆