tags:

views:

84

answers:

3

Take a look at this code:

public class Test {
public static void main(String... args) {
    flipFlop("hello", new Integer(4), 2004);
    // flipFlop("hello", 10, 2004); // this works!
}

private static void flipFlop(String str, int i, Integer iRef) {
    System.out.println(str + " (String, int, Integer)");
}

private static void flipFlop(String str, int i, int j) {
    System.out.println(str + " (String, int, int)");
}

}

The compiler gives an error that the invocation is ambiguous:

Description Resource Path Location Type The method flipFlop(String, int, Integer) is ambiguous for the type Test Test.java scjp19 - inheritence/src line 3 Java Problem

But if the commented-out line is used ti invoke flip-flop, the method is unambiguously invoked (the second one, because autoboxing comes after using the primitive itself).

I would expect the compiler to see that the second argument will be unboxed one way or the other, and judge what method must be invoked depending on the third argument. Why does not this happen? What is the rationale?

+6  A: 

Commented line matches flipFlop(String str, int i, int j) exactly. The other line matches both because of autoboxing.

fastcodejava
+1  A: 

flipFlop("hello", new Integer(4), 2004); is incompatible with flipFlop(String str, int i, Integer iRef)

CadetNumber1
I don't think it is... Java 5 and later supports automatic boxing/unboxing between primitives and their Wrapper classes. In this case between int and Integer. Comment out the second method and see for yourself.
Markos Fragkakis
A: 

Java 5 and later do auto-boxing (convert Integer to int) hence the result.

Taranfx