Java泛型 - 将子类列表分配给超类列表 [英] Java Generics -- Assigning a list of subclass to a list of superclass

查看:100
本文介绍了Java泛型 - 将子类列表分配给超类列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



所以我有类似下面的内容:

  B类扩展A; 

列表< B> bList = new ArrayList< B>();
列表< A> aList = bList;

为什么最后一项任务失败?对于新手问题抱歉

解决方案

为了解释这一点,让我用Integer替换B,用Number替换A。这只是为了使它更容易解释。

 类Integer extends Number; 

列表<整数> iList = new ArrayList< Integer>();
列表<号码> nList = iList //会失败

这会失败的原因是因为nList可以取任何数字 - 它可以采用Integer,它可以采用Double,或者Number的任何子类。但是,这不适用于iList。您不能将Double添加到iList,因为它仅接受Integer及其子类。希望这有助于向你解释。


I have a basic question regarding assignment of a list of subclass to a list of superclass.

So I have something like the following:

Class B extends A;

List <B> bList = new ArrayList<B>();
List <A> aList = bList; 

Why does this last assignment fail? Sorry for the newbie question

解决方案

To explain this, let me substitute "B" with Integer and "A" with Number. This is just to make it a little easier to explain.

Class Integer extends Number;

List <Integer> iList = new ArrayList<Integer>();
List <Number> nList = iList // will fail

The reason this would fail is because nList can take any Number -- it can take Integer, it can take Double, or for that matter any subclass of Number. However, this is not true for iList. You cannot add a Double to iList because it accepts only Integer and its subclasses. Hope this helps explain it to you.

这篇关于Java泛型 - 将子类列表分配给超类列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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