Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Strange generic compilation behaviour - also javac/eclipse difference

843793Jul 8 2009 — edited Jul 8 2009
Hello!

With my friends I've stumbled upon a problem in understanding how the compiler (and Java Language Specification too) treats a specific generic declaration.
public class Main {
    public static void main(String args[]) {
        ArrayList<Integer> inParam2 = new ArrayList<Integer>();
        List<Number> returnValue2 = justDoIt(inParam2);
    }

    public static <E extends Number> List<E> justDoIt(List<? super E> nums) {
        return null;
    }
}
The code compiles fine with javac and throws compile error in eclipse. The latter, I believe, is the proper behaviour - what am I missing? The method justDoIt could be possibly resolved in two ways:
public static List<Number> justDoIt(List<Number> nums)
or
public static List<Integer> justDoIt(List<Integer> nums)
both will give reasonable and well-documented compile time errors. The first is because ArrayList<Integer> can't be passed to List<Number> (and even more - Integer is not a supertype of Number, therefore <? super Number> should fail). The latter is because List<Integer> value can't be assigned to List<Number> na main() for obvious reasons. I suppose from these two the compiler would resolve the mentioned static function as the one with Number throughout the declaration... but what really happens? How come the code compiles?

I would be very grateful for any insights.


Best regards,
Mateusz
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 5 2009
Added on Jul 8 2009
1 comment
83 views