Java泛型 - 将子类列表分配给超类列表 [英] Java Generics -- Assigning a list of subclass to a list of superclass
问题描述
所以我有类似下面的内容:
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屋!