Deepa Sobin wrote:In that case, why does the below code fail to add a Number into this list which can hold any super type of Integer?
You use ? when you don't know what the specific type of the objects in the collection will be, but in this case you know the array either holds Integer objects or objects of some superclass of Integer.
Remember, the compiler only looks at the reference type of intList, not the object type. Two possibilities are that it could be an ArrayList<Number>, or perhaps an ArrayList<Integer>. As far as the compiler knows, it could be either one. So it only makes sense for the compiler to allow you to add elements which pass the IS-A
test for the
type declared in List<? super
type>, since those objects would definitely also pass the IS-A test for any superclass of
type.
Effectively that means you can only add Integer objects, or any objects of any subclass of Integer, to that List. It just so happens that Integer has no subclasses, so only Integer objects may be added.