Generic extend can't add the same type

前端 未结 3 2007
甜味超标
甜味超标 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:36

    When you have a variable with a wildcard, and a method that takes the generic type parameter, Java cannot ensure type safety. It must disallow this call.

    Consider a List for example. You may have assigned it List, but the variable could be assigned a List. You shouldn't be allowed to add a Dog to such a list.

    To allow the add method to be called, remove the wildcard.

    public void takeList(List list){
    

    Besides, String is final, so there really is no point to saying ? extends String.

提交回复
热议问题