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

前端 未结 7 2092
我寻月下人不归
我寻月下人不归 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 03:04

    List<B> is not List<A>:

    Through example: let say you have class B1 extends A{} and class B2 extends A{} then (if you would be able to do that:

    List<B1> b1 = new AList<B1>();
    List<A> a = b1;
    
    List<B2> b2 = new AList<B2>();
    

    by the hypothesis, you should be able to do a.add(new B2()) but this is wrong.

    If you try the same thing but using arrays instead of lists, it will compile and throw exception in runtime.

    We say that arrays are covariant and generics are invariant.

    to make the code compile you have the wite it:

    List<? extends A> a = b;
    

    this says that a is a list of some subtype of A. _But you don know which one. Because of that you can't do a.put(X)

    0 讨论(0)
提交回复
热议问题