Book - java generics and collection by Maurice Naftalin and Philip Wadler
page no. 19
The Get and Put Principle: use an extends wildcard when you only get values out of a
structure, use a super wildcard when you only put values into a structure, and don’t use
a wildcard when you both get and put.
though book has explained it with some codes, i didn't understand what does it actually means. why we can't put the value while using wildcard (? extends T) and why cant we put the value while using (? super T) ??
This will fail compilation at the add operation. This is because the compiler doesn't know if numberList is actually List<Integer> or List<Float> or something else (as these all fit ? extends Number). So the compiler can't let you add Integer to it. So put/add is not allowed when using extends wildcard.
Similarly, if you are using super wildcard, then put/add works but get doesn't work
Here the opposite case happens, the compiler doesn't know if numberList is actually List<Integer> or List<Number> or List<Object> (as these all fit <? super Integer>). So you can't get an element into Integer object, as the list might actually be List<Number> and might contain Float objects. But add/put works fine, because regardless of whether numberList is List<Integer> or List<Number>, Integer objects can be added to the list. Hope that helps...