Sandra Bachan wrote:
Malte Wannerskog wrote:
The key point to remember is that List<? super Cat> does not mean you can add Cat or any supertype of Cat. It means that the generic type will be Cat or any supertype of Cat. When you think about it that way it should be clear why you can only add Cats or subtypes of Cat (in your case String or subtypes of String (which of course will be quite difficult
)).
Please show an example of adding the generic type of Cat or any supertype of Cat. I'm confused too!
You can only add Cats or
subtypes of Cat,
not supertypes.
The way
you should think when you see <? super Cat> is that the generic type of the list could be Cat or any supertype of Cat:
All four options above are possible, the compiler does not know which generic type the list is, only that it's Cat or supertype of Cat.
Now what is true for list1,list2,list3 and list4? Which type of objects does the compiler know for certain that we can add to all 4 lists...?
... Only Cats and Kittens since the following holds true:
Cat Is-A(n) Animal
Cat Is-A Life
Cat Is-A(n) Object
Kitten Is-A Cat (and therefore also Is-A(n) Animal, Life and Object).
If you saw
The compiler would not allow you inserting Life into the list since
Life Is-A(n) Animal does
not hold true.
If the compiler knew that the generic type was animal it would allow Animal, Cat or Kitten.
But when you type <? super Cat> it doesnt know wether the generic type will be Cat, Animal, Life or Object.
Therefore only Cats and Kittens are safe to add.