Understanding wildcards in Java generics

后端 未结 7 1632
不思量自难忘°
不思量自难忘° 2020-12-31 11:07

I\'m not sure why the last statement in the following code is illegal. Integer should be a subtype of ?, so why can\'t I assign it to b

7条回答
  •  暖寄归人
    2020-12-31 11:49

    Here is a short summary of what you can and cannot do with generics:

        List listOfAnyNumbers = null;
        List listOfNumbers = null;
        List listOfIntegers = null;
        listOfIntegers = listOfNumbers;     // Error - because listOfNumbers may contain non-integers
        listOfNumbers = listOfIntegers;     // Error - because to a listOfNumbers you can add any Number, while to listOfIntegers you cannot.
        listOfIntegers = listOfAnyNumbers;  // Error - because listOfAnyNumbers may contain non-integers  
        listOfAnyNumbers = listOfIntegers;  // OK    - because listOfIntegers is a list of ?, where ? extends Number.
        listOfNumbers = listOfAnyNumbers;   // Error - because listOfAnyNumbers may actually be List, to which you cannot add any Number. 
        listOfAnyNumbers = listOfNumbers;   // OK    - because listOfNumbers is a list of ?, where ? extends Number.
    

提交回复
热议问题