Java Generic with ArrayList <? extends A> add element

前端 未结 6 939
遇见更好的自我
遇见更好的自我 2020-12-03 20:51

I have classes A, B, C and D where B extends A, C extends A and

6条回答
  •  时光说笑
    2020-12-03 21:18

    ArrayList means an ArrayList of some unknown type that extends A.
    That type might not be C, so you can't add a C to the ArrayList.

    In fact, since you don't know what the ArrayList is supposed to contain, you can't add anything to the ArrayList.

    If you want an ArrayList that can hold any class that inherits A, use a ArrayList.

提交回复
热议问题