Could you please explain, why this snippet (K&B scjp 5 book, ch. 7 self test, q. 16, C) wouldn't compile?
The K&B explanation says "C is wrong because the return type evaluates to List<Integer>, and that can't be assigned to a variable of type List<Number>." I thought that E evaluates to Integer here, thus having <? super E> for the return type would be ok?
The return type doesn't evaluate to Integer. If you try this
In fact, the return type is not known, it says List<? super E> or in the current call List<? super Integer>, thus the list can be of any type, not necessarily Integer or Number. You can't even catch the returned value in List<Object> as the type of the returned list is actually not known. You can only catch it in an untyped list.
I just looked up in my book and the statement actually looks like this
The method process returns List<? super Integer> and this cannot be assigned to List<Number> because we want output to contain only Numbers. Whereas the returned list can contain objects of any supertype of Integer, eg. Object. Since Object is-not-a Number, it could create problems later at runtime.
Thanks a lot! I think I got that, the return type of a method can potentialy be few levels "higher" than the variable's type we are assigning it to. So if we use E = Integer, then super E can be not necessarily a Number (which would work), but even Object (which wouldn't work).
You will always be treated with dignity. Now, strip naked, get on the probulator and hold this tiny ad: