Reputation: 1165
Firstly, why does the first line compile while the second does not? Secondly, in the case of the second line, do both types always need to be the same i.e Integer on the left and Integer on the right. Or is it possible to have different types on the left and the right?
List<? super Integer> nums1 = new ArrayList<Number>(); //COMPILES
List<Integer> nums2 = new ArrayList<Number>(); //DOES NOT COMPILE
Upvotes: 0
Views: 65
Reputation: 5449
Your question is esentially a duplicate of this SO-article but in short:
? super T
means "anything that is a superclass of T". Number
is a superclass of Integer
so this is accepted. The second line doesn't work simply because Number
is not Integer
. It wouldn't work vice versa, either so
ArrayList<Number> nums2 = new ArrayList<Integer>();
leads to a compile error as well. For that you can use
ArrayList<? extends Number> nums2 = new ArrayList<Integer>();
Upvotes: 2