Tried to compile on java 1.5.11 and got the following error message:
Type mismatch: cannot convert from List<capture-of ? super Number> to List<Number>
But wait - the fun's only about to begin
Change the types of both output and input reference variables to List<Number> - You'll get the same stuff. Change output to List<Number> and input to List<Integer> - same stuff.
TYhe problem is in the return type.
Let's analyse that: 1.) E is any type that passes IS-A test for being a Number. Both Number and Integer play along, so if we're either passing a list of Numbers or a list of Integers as a method's param - it's OK.
2.) The return type is something that is a supertype to the type we passed.
So if I passed a list of Integers, I would expect to be able to assign the returned reference to the reference types: List<Object>, List<Number> or List <Integer>. If I was to pass a list of Numbers, I would expect the compiler would let me assign the returned value to the reference types: List<Object> and List<Number>.
But instead - I get that weird looking error message. I checked the same with 'extends' frame - same thing.
Does it mean that I can't specify 'fuzzy' generic return types - only the solid ones?
As you said before E could be a Number or anything that extends Number. Some examples:
1) If E is an Integer, your method signature will resolve to:
The return type can be any List whose element extends Integer; that would be List<Integer>, List<Number> and List<Object>. Now, imagine the following:
Because a List of Objects is not the same as a List of Integers (even if an Integer is an Object).
- If E is Number, then your method signature will resolve to:
Here, again, the following won't work:
The same logic applies: a List of Numbers is not a List of Objects. (Think about this: a List of Objects can hold Strings as well as Numbers and any object of any class out there; however, a List of Numbers can only hold Numbers and its subtypes.)
I hope those examples made it a little clearer for you.
[Edit] Your example could be corrected in this way:
[ June 10, 2007: Message edited by: Sergio Tridente ]