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?

Markos Fragkakis
  • 7,499
  • 18
  • 65
  • 103
  • 2
    Dupe: http://stackoverflow.com/questions/501412/why-does-autoboxing-make-some-calls-ambiguous-in-java – BalusC Mar 07 '10 at 17:13

4 Answers4

6

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

fastcodejava
  • 39,895
  • 28
  • 133
  • 186
1

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

Ashish Yadav
  • 1,667
  • 6
  • 20
  • 26
  • 1
    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 Mar 07 '10 at 17:28
0

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

Taranfx
  • 51
  • 1
  • 1
  • 3
-1

yes, acc to ques, invocation should depend on difference between int / Integer @ 3rd argument. but here even the difference @ 3rd argument does matter if 2nd arg is autoUnboxed.

even this does work: flipFlop("hex", new Integer(4), new Integer(17));

while acc to syntex and auto box feature, this should call :: "private static void flipFlop(String str, int i, Integer iRef) " method, but all it saying is AMBIGUOUS .....??

nitin1706
  • 395
  • 3
  • 4
  • 1
    Using full words (acc --> according, ques --> question, @ --> at) will make your answer more readable and helpful for other SO members. – Markos Fragkakis Jan 03 '12 at 10:01