I understand that using a lower bounded wildcard on a list as method parameter should let us put elements of that lower bound and its super types but consider following code:
public class WildcardError {
void foo(List<? super Number> i) {
i = new ArrayList<Integer>(); //compile error
i.add(new Integer(2)); // no error
}
}
Now here I understand why there is a compile error in the first statement of method foo as ArrayList of Integer is not a subtype of List of "? super Number" but then why are we allowed to put Integer in this list even though integer is not a supertype of Number? Also it is the other way around in following code:
public class WildcardError {
void foo(List<? super Integer> i) {
i = new ArrayList<Number>(); //no error
Number k =20;
i.add(k); // compile error
}
}
Here I understand there should be no compile error in statement 2 since ArrayList of Number is a subtype of List of "? super Integer" but why is there a compile error on last statement?
Even though ? super Integer should accommodate super class Number.
I've tried to find the answer but can't search the exact scenario.