Java Generics — Assigning a list of subclass to a list of superclass

前端 未结 7 2104
我寻月下人不归
我寻月下人不归 2020-12-07 02:00

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          


        
7条回答
  •  孤街浪徒
    2020-12-07 02:40

    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  iList = new ArrayList();
    List  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.

提交回复
热议问题