Generic extend can't add the same type

前端 未结 3 2046
甜味超标
甜味超标 2021-01-25 11:45

I\'m new to these generic types. In the below code, I created a method that accepts a List of items that extends \"String\".

My Question? - When the list can be assigned

3条回答
  •  忘了有多久
    2021-01-25 12:33

    Because it's not the runtime type that's relevant here. list is still of type List, you've just happened to assign it to a new ArrayList(). Consider this:

    list = rand() ? new ArrayList() : new ArrayList();
    

    The compiler could not possibly tell if list.add("test") will be valid -- it only makes decisions based on the compile-time type of list.

    Note that in reality nothing extends String, it's a final class.

提交回复
热议问题