user1883212
user1883212

Reputation: 7859

Ambiguous parameter for the compiler, when it's not ambiguous for me

Why is the compiler complaining here?

public static void main(String[] args) {
    flipFlop(new Integer(11), 20f);
}

private static void flipFlop(int i, Float iRef) {

}

private static void flipFlop(int i, float j) {

}

But not here?

public static void main(String[] args) {
    flipFlop(11, 20f);
}

private static void flipFlop(int i, Float iRef) {

}

private static void flipFlop(int i, float j) {

}

That's strange because it should resolve in both cases.

Only the second parameter could become ambiguous in some cases but not the first. So why is it complaining if I change the first.

Upvotes: 2

Views: 83

Answers (4)

Jonathan Rosenne
Jonathan Rosenne

Reputation: 2217

Your second example matches the signature of the second flipFlop. The first call matches neither flipFlops, so the compiler attempts to select the most specific match, and both are equally specific because both require boxing/unboxing to match. Since they are equally applicable, the call is ambiguous.

See the Java Language Specification, Clause 15.12 Method Invocation Expressions.

Upvotes: 0

Java Panter
Java Panter

Reputation: 307

In first case you box the value into and Integer,and it is not unboxed when received as is should be and int,the JVM does not do unboxing in case of arguments. In the second case you give a primitive type int to the int argument and the second argument is autoboxed.

Upvotes: 0

assylias
assylias

Reputation: 328598

When several methods are applicable, the compiler tries to find the most specific one. If two methods are maximally specific, there is an ambiguity and you get an error.

In summary (the actual rules are a little more complicated):

  • the compiler first looks for applicable methods without allowing varargs or (un-)boxing. In your second example, only the second method applies and is chosen. In your first example, unboxing of Integer is required and no method can be chosen at this stage.
  • the compiler then allows boxing and unboxing. In your first example, both methods are applicable.
  • the compiler then determines which method is more specific: in your case, none is more specific in the sense defined in the specifications because there is no relationship between float and Float (examples: if you had a float and a double, float would be more specific; if you had a Float and a Number, Float would be more specific).

Upvotes: 4

Phylogenesis
Phylogenesis

Reputation: 7880

In the second case you have an exact match for the method signature. In the first case it's ambiguous. Do you unbox the Integer or box the Float?

Upvotes: 1

Related Questions