Overloading function using varargs - java

This will not compile:
public class Methods
{
public static void method(Integer... i)
{
System.out.print("A");
}
public static void method(int... i)
{
System.out.print("B");
}
public static void main(String args[])
{
method(7);
}
}
This will compile and work:
public class Methods
{
public static void method(Integer i)
{
System.out.print("A");
}
public static void method(int i)
{
System.out.print("B");
}
public static void main(String args[])
{
method(7);
}
}
First and second example are very similar. First uses varargs, second not. Why one works, second not. 7 is primitive, so second method should be called in both cases. Is it normal behaviour?
I found it:
Bug report
Stack overflow

This is a high-level informal summary of what is going on.
Firstly varargs syntax is really just syntactic sugaring for passing an array. So method(7) is actually going to pass an array of ... something.
But an array of what? There are two options here corresponding to the two overloads of the method; i.e an int[] or a Integer[].
If there are two or more overloads that could work (i.e. right method names, right numbers of arguments, convertible values) then the resolution process will chose the overload that is an exact match over a match that requires conversions, and complain if the only candidates require conversions. (This is a drastic simplification of the rules ... see the JLS section 15.12 for the complete story ... and be prepared for a long / difficult read!)
So what is happening in your first example is that it is trying to decide between two methods that both require conversions; i.e. int to int[] versus int to Integer[]. Basically it cannot decide which alternative to use. Hence a compilation error that says that the call is ambiguous.
If you change the varargs call to a call passing an explicit Integer[] or int[], you now get an exact match to one of the two overloads ... and the rules above say that this is not ambiguous.
I understand it as: 7 is primitive so it should be converted to array - int[].
The problem is that 7 can also be converted to an Integer[] ... by auto-boxing the int first.

Multiple arguments must be passed in an array, but the varargs hides the process. In the above varargs method, parameter acts as an int array with a reference name.
So if you change it to:
public static void main(String args[])
{
int[] s = {7};
method(s);
}
first class will compile and work properly.

The answer is rather difficult. But it is described in the JLS §15.12. Method Invocation Expressions. In these specifications, "variable arity" methods are methods with variable number of arguments, so varargs.
§15.12.2.4. Phase 3: Identify Applicable Variable Arity Methods
The method m is an applicable variable-arity method if and only if all
of the following conditions hold:
For 1 ≤ i < n, the type of ei, Ai, can be converted by method
invocation conversion to Si.
If k ≥ n, then for n ≤ i ≤ k, the type of ei, Ai, can be converted by
method invocation conversion to the component type of Sn.
If k != n, or if k = n and An cannot be converted by method invocation
conversion to Sn[], then the type which is the erasure (§4.6) of Sn is
accessible at the point of invocation.
If m is a generic method as described above, then Ul <:
Bl[R1=U1...,Rp=Up] (1 ≤ l ≤ p).
If no applicable variable arity method is found, a compile-time error
occurs.
Otherwise, the most specific method (§15.12.2.5) is chosen among the
applicable variable-arity methods.
So, we should look further to §15.12.2.5.
§15.12.2.5. Choosing the Most Specific Method
One variable arity member method named m is more specific than another
variable arity member method of the same name if either:
One member method has n parameters and the other has k parameters,
where n ≥ k, and:
The types of the parameters of the first member method are T1, ...,
Tn-1, Tn[].
The types of the parameters of the other method are U1, ..., Uk-1,
Uk[].
If the second method is generic then let R1 ... Rp (p ≥ 1) be its type
parameters, let Bl be the declared bound of Rl (1 ≤ l ≤ p), let A1 ...
Ap be the type arguments inferred (§15.12.2.7) for this invocation
under the initial constraints Ti << Ui (1 ≤ i ≤ k-1) and Ti << Uk (k ≤
i ≤ n), and let Si = Ui[R1=A1,...,Rp=Ap] (1 ≤ i ≤ k).
Otherwise, let Si = Ui (1 ≤ i ≤ k).
For all j from 1 to k-1, Tj <: Sj, and,
For all j from k to n, Tj <: Sk, and,
If the second method is a generic method as described above, then
Al <: Bl[R1=A1,...,Rp=Ap] (1 ≤ l ≤ p).
(T <: S means T is a subtype of S)
Your methods do not match these conditions, so there is no "Most Specific" method. So, it says a little bit further:
It is possible that no method is the most specific, because there are
two or more methods that are maximally specific. In this case:
If all the maximally specific methods have override-equivalent
(§8.4.2) signatures, then:
If exactly one of the maximally specific methods is not declared
abstract, it is the most specific method.
Otherwise, if all the maximally specific methods are declared
abstract, and the signatures of all of the maximally specific methods
have the same erasure (§4.6), then the most specific method is chosen
arbitrarily among the subset of the maximally specific methods that
have the most specific return type.
However, the most specific method is considered to throw a checked
exception if and only if that exception or its erasure is declared in
the throws clauses of each of the maximally specific methods.
Otherwise, we say that the method invocation is ambiguous, and a
compile-time error occurs.
So, the conclusion: your methods are ambiguous following the JLS.

Related

Why ambiguous error when using varargs overloading with primitive type and wrapper class? [duplicate]

This question already has answers here:
Ambiguous varargs methods
(4 answers)
Closed 6 years ago.
I do not understand why here in case 1, it is not giving compilation error, contrary in case 2 (varargs), it gives compilation error. Can anyone please elaborate what differences the compiler makes in these two cases? I went through many posts about it, but not able to understand it yet.
Case #1
public class Test {
public void display(int a) {
System.out.println("1");
}
public void display(Integer a) {
System.out.println("2");
}
public static void main(String[] args) {
new Test().display(0);
}
}
The Output is: 1
Case #2
public class Test {
public void display(int... a) {
System.out.println("1");
}
public void display(Integer... a) {
System.out.println("2");
}
public static void main(String[] args) {
new Test().display(0);
}
}
Compilation Error:
The method display(int[]) is ambiguous for the type Test
In your first example the display(int) method is invoked in strict invocation context while display(Integer) is invoked in loose invocation context (since auto-boxing is required). Thus the compiler chooses the display(int) method according to JLS. Invocation contexts are explained here JLS 5.3. Invocation Contexts
In the second example both methods are invoked in loose invocation context thus the compiler needs to find the most specific method JLS 15.12.2.5 Choosing the Most Specific Method. Since int is not a subtype of Integer there is no most specific method and the compiler throws a compilation error.
You can find my explanation for a similar compilation error here Method overload ambiguity with Java 8 ternary conditional and unboxed primitives
The parts that apply to this case:
Identifying applicable methods is divided into 3 phases.
The first phase (§15.12.2.2) performs overload resolution without
permitting boxing or unboxing conversion, or the use of variable
arity method invocation. If no applicable method is found during
this phase then processing continues to the second phase.
The second phase (§15.12.2.3) performs overload resolution while
allowing boxing and unboxing, but still precludes the use of
variable arity method invocation. If no applicable method is found
during this phase then processing continues to the third phase.
The third phase (§15.12.2.4) allows overloading to be combined with
variable arity methods, boxing, and unboxing.
For the first example only the display(int) method is matched on the first phase thus it is chosen. For the second example both methods are matched on the 3rd phase thus the Choosing the Most Specific Method algorithm comes into play JLS 15.12.2.5 Choosing the Most Specific Method:
m2 is not generic, and m1 and m2 are applicable by variable arity
invocation, and where the first k variable arity parameter types of m1
are S1, ..., Sk and the first k variable arity parameter types of m2
are T1, ..., Tk, the type Si is more specific than Ti for argument ei
for all i (1 ≤ i ≤ k). Additionally, if m2 has k+1 parameters, then
the k+1'th variable arity parameter type of m1 is a subtype of the
k+1'th variable arity parameter type of m2.
As mentioned earlier there is no most specific method since int <: Integer does not satisfy.
After java Version 1.5 there is a cool feature introduced named autoboxing which enables compiler to Convert a primitive type to a Wrapper Type. So, during compilation both method will be work same.
public void display(int... a) {
System.out.println("1");
}
public void display(Integer... a) {
System.out.println("2");
}
both the function will be treated as a same method because of autoboxing performs during the compilation . So Be Beware of Autoboxing while overloading method in Java.
More you find Here..
Best Practices Of Method Overloading

Java method overloading - Generic parameter & parameters within same inheritance tree

Let's assume I have following code:
// Method acception generic parameter
public static <T> T foo(T para) {
return para;
}
// Method accepting Integer parameter
public static Integer foo(Integer para) {
return para + 1;
}
// Method accepting Number parameter
public static Number foo(Number para) {
return para.intValue() + 2;
}
public static void main(String[] args) {
Float f = new Float(1.0f);
Integer i = new Integer(1);
Number n = new Integer(1);
String s = "Test";
Number fooedFloat = foo(f); // Uses foo(Number para)
Number fooedInteger = foo(i); // Uses foo(Integer para)
Number fooedNumber = foo(n); // Uses foo(Number para)
String fooedString = foo(s); // Uses foo(T para)
System.out.println("foo(f): " + fooedFloat);
System.out.println("foo(i): " + fooedInteger);
System.out.println("foo(n): " + fooedNumber);
System.out.println("foo(s): " + fooedString);
}
The output looks the following:
foo(f): 3
foo(i): 2
foo(n): 3
foo(s): Test
Now the question(s):
foo(n) calls foo(Number para), most probably because n is defined as Number, even though it has an Integer assigned to it. So am I right in the assumption that the decision, which of the overloaded methods is taken happens at compile-time, without dynamic binding? (Question about static and dynamic binding)
foo(f) uses foo(Number para), while foo(i) uses foo(Integer para). Only foo(s) uses the generic version. So the compiler always looks if there is a non-generic implementation for the given types, and only if not it falls back to the generic version? (Question about generics)
Again, foo(f) uses foo(Number para), while foo(i) uses foo(Integer para). Yet, Integer i would also be a Number. So always the method with the "outer-most" type within the inheritance tree is taken? (Question about inheritance)
I know these are a lot questions, and the example is not taken from productive code, yet I just would like to know what "happens behind" and why things happen.
Also any links to the Java documentation or the Java specification are really appreciated, I could not find them myself.
The rules of determining which method signature to call at compile-time are explained in the language specification. Specifically important is the section on choosing the most specific method. Here are the parts related to your questions:
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
...
One applicable method m1 is more specific than another applicable method m2, for an invocation with argument expressions e1, ..., ek, if any of the following are true:
m2 is generic, and m1 is inferred to be more specific than m2 for argument expressions e1, ..., ek by §18.5.4.
m2 is not generic, and m1 and m2 are applicable by strict or loose invocation, and where m1 has formal parameter types S1, ..., Sn and m2 has formal parameter types T1, ..., Tn, the type Si is more specific than Ti for argument ei for all i (1 ≤ i ≤ n, n = k).
...
A type S is more specific than a type T for any expression if S <: T (§4.10).
In this case, Integer is more specific than Number because Integer extends Number, so whenever the compiler detects a call to foo that takes a variable declared of type Integer, it will add an invocation for foo(Integer).
More about the first condition related to the second method being generic is explained in this section. It's a little verbose but I think the important part is:
When testing that one applicable method is more specific than another (§15.12.2.5), where the second method is generic, it is necessary to test whether some instantiation of the second method's type parameters can be inferred to make the first method more specific than the second.
...
Let m1 be the first method and m2 be the second method. Where m2 has type parameters P1, ..., Pp, let α1, ..., αp be inference variables, and let θ be the substitution [P1:=α1, ..., Pp:=αp].
...
The process to determine if m1 is more specific than m2 is as follows:
...
If Ti is a proper type, the result is true if Si is more specific than Ti for ei (§15.12.2.5), and false otherwise. (Note that Si is always a proper type.)
Which basically means that foo(Number) and foo(Integer) are both more specific than foo(T) because the compiler can infer at least one type for the generic method (e.g. Number itself) that makes foo(Number) and foo(Integer) more specific (this is because Integer <: Number and Number <: Number) .
This also means that in your code foo(T) is only applicable (and inherently the most specific method since it's only the one applicable) for the invocation that passes a String.
Am I right in the assumption that the decision, which of the overloaded methods is taken happens at compile-time, without dynamic binding?
Yes, Java chooses among available overloads of a method at compile time, based on the declared types of the arguments, from among the alternatives presented by the declared type of the target object.
Dynamic binding applies to choosing among methods having the same signature based on the runtime type of the invocation target. It has nothing directly to do with the runtime types of the actual arguments.
So the compiler always looks if there is a non-generic implementation for the given types, and only if not it falls back to the generic version?
Because of type erasure, the actual signature of your generic method is
Object foo(Object);
Of the argument types you tested, that is the best match among the overloaded options only for the String.
So always the method with the "outer-most" type within the inheritance tree is taken?
More or less. When selecting among overloads, the compiler chooses the alternative that best matches the declared argument types. For a single argument of reference type, this is the method whose argument type is the argument's declared type, or its nearest supertype.
Things can get dicey if Java has to choose among overloads of multiple-argument methods, and it doesn't have an exact match. When there are primitive arguments, it also has to consider the allowed argument conversions. The full details take up a largish section of the JLS.
So, it is pretty simple:
1) Yes, the decision is made at compile-time. The compiler chooses the method with the most specific matching type. So the compiler will choose the Number version when the variable you pass as an argument is declared as a Number, even if it is an Integer at run-time. (If the compiler finds two "equally matching" methods, an ambiguous method error will make the compilation fail)
2) At run-time, there are no generics, everything is just an Object. Generics are a compile-time and source-code feature only. Therefore the compiler must do the best he can, because the VM surely can not.

Method overload ambiguity with Java 8 ternary conditional and unboxed primitives

The following is code compiles in Java 7, but not openjdk-1.8.0.45-31.b13.fc21.
static void f(Object o1, int i) {}
static void f(Object o1, Object o2) {}
static void test(boolean b) {
String s = "string";
double d = 1.0;
// The supremum of types 'String' and 'double' is 'Object'
Object o = b ? s : d;
Double boxedDouble = d;
int i = 1;
f(o, i); // fine
f(b ? s : boxedDouble, i); // fine
f(b ? s : d, i); // ERROR! Ambiguous
}
The compiler claims the last method call ambiguous.
If we change the type of the second parameter of f from int to Integer, then the code compiles on both platforms. Why doesn't the posted code compile in Java 8?
Let's first consider a simplified version that doesn't have a ternary conditional and doesn't compile on Java HotSpot VM (build 1.8.0_25-b17):
public class Test {
void f(Object o1, int i) {}
void f(Object o1, Object o2) {}
void test() {
double d = 1.0;
int i = 1;
f(d, i); // ERROR! Ambiguous
}
}
The compiler error is:
Error:(12, 9) java: reference to f is ambiguous
both method f(java.lang.Object,int) in test.Test and method f(java.lang.Object,java.lang.Object) in test.Test match
According to JLS 15.12.2. Compile-Time Step 2: Determine Method Signature
A method is applicable if it is applicable by one of strict invocation (§15.12.2.2), loose invocation (§15.12.2.3), or variable arity invocation (§15.12.2.4).
Invocation has to do with invocation context which is explained here JLS 5.3. Invocation Contexts
When no boxing or unboxing is involved for a method invocation then strict invocation applies. When boxing or unboxing is involved for a method invocation then loose invocation applies.
Identifying applicable methods is divided into 3 phases.
The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.
The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.
The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.
For our case there are no methods applicable by strict invocation. Both methods are applicable by loose invocation since the double value has to be boxed.
According to JLS 15.12.2.5 Choosing the Most Specific Method:
If more than one member method is both accessible and applicable to a
method invocation, it is necessary to choose one to provide the
descriptor for the run-time method dispatch. The Java programming
language uses the rule that the most specific method is chosen.
Then:
One applicable method m1 is more specific than another applicable
method m2, for an invocation with argument expressions e1, ..., ek, if
any of the following are true:
m2 is generic, and m1 is inferred to be more specific than m2 for
argument expressions e1, ..., ek by §18.5.4.
m2 is not generic, and m1 and m2 are applicable by strict or loose
invocation, and where m1 has formal parameter types S1, ..., Sn and m2
has formal parameter types T1, ..., Tn, the type Si is more specific
than Ti for argument ei for all i (1 ≤ i ≤ n, n = k).
m2 is not generic, and m1 and m2 are applicable by variable arity
invocation, and where the first k variable arity parameter types of m1
are S1, ..., Sk and the first k variable arity parameter types of m2
are T1, ..., Tk, the type Si is more specific than Ti for argument ei
for all i (1 ≤ i ≤ k). Additionally, if m2 has k+1 parameters, then
the k+1'th variable arity parameter type of m1 is a subtype of the
k+1'th variable arity parameter type of m2.
The above conditions are the only circumstances under which one method may be more specific than another.
A type S is more specific than a type T for any expression if S <: T (§4.10).
It may look that the 2nd condition matches for this case but in fact it doesn't because int is not a subtype of Object: it's not true that int <: Object. However if we replace int with Integer in the f method signature this condition would match. Note that the 1st parameter in methods matches this condition since Object <: Object is true.
According to $4.10 no subtype/supertype relation is defined between primitive types and Class/Interface types. So int is not a subtype of Object for example. Thus int is not more specific than Object.
Since among the 2 methods there are no more specific methods thus there can be no strictly more specific and can be no most specific method (the JLS gives definitions for those terms in the same paragraph JLS 15.12.2.5 Choosing the Most Specific Method). So both methods are maximally specific.
In this case the JLS gives 2 options:
If all the maximally specific methods have override-equivalent signatures (§8.4.2) ...
This is not our case, thus
Otherwise, the method invocation is ambiguous, and a compile-time error occurs.
The compile-time error for our case looks valid according to the JLS.
What happens if we change method parameter type from int to Integer?
In this case both methods are still applicable by loose invocation. However the method with Integer parameter is more specific than the method with 2 Object parameters since Integer <: Object. The method with Integer parameter is strictly more specific and most specific thus the compiler will choose it and not throw a compile error.
What happens if we change double to Double in this line: double d = 1.0;?
In this case there is exactly 1 method applicable by strict invocation: no boxing or unboxing is required for invocation of this method: f(Object o1, int i). For the other method you need to do boxing of int value so it's applicable by loose invocation. The compiler can choose the method applicable by strict invocation thus no compiler error is thrown.
As Marco13 pointed out in his comment there is a similar case discussed in this post Why is this method overloading ambiguous?
As explained in the answer there were some major changes related to the method invocation mechanisms between Java 7 and Java 8. This explains why the code compiles in Java 7 but not in Java 8.
Now comes the fun part!
Let's add a ternary conditional operator:
public class Test {
void f(Object o1, int i) {
System.out.println("1");
}
void f(Object o1, Object o2) {
System.out.println("2");
}
void test(boolean b) {
String s = "string";
double d = 1.0;
int i = 1;
f(b ? s : d, i); // ERROR! Ambiguous
}
public static void main(String[] args) {
new Test().test(true);
}
}
The compiler complains about ambiguous method invocation.
The JLS 15.12.2 doesn't dictate any special rules related to ternary conditional operators when performing method invocations.
However there are JLS 15.25 Conditional Operator ? : and JLS 15.25.3. Reference Conditional Expressions. The former one categorizes conditional expressions into 3 subcategories: boolean, numeric and reference conditional expression. The second and third operands of our conditional expression have types String and double respectively. According to the JLS our conditional expression is a reference conditional expression.
Then according to JLS 15.25.3. Reference Conditional Expressions our conditional expression is a poly reference conditional expression since it appears in an invocation context. The type of our poly conditional expression thus is Object (the target type in the invocation context). From here we could continue the steps as if the first parameter is Object in which case the compiler should choose the method with int as the second parameter (and not throw the compiler error).
The tricky part is this note from JLS:
its second and third operand expressions similarly appear in a context of the same kind with target type T.
From this we can assume (also the "poly" in the name implies this) that in the context of method invocation the 2 operands should be considered independently. What this means is that when the compiler has to decide whether a boxing operation is required for such argument it should look into each of the operands and see if a boxing may be required. For our specific case String doesn't require boxing and double will require boxing. Thus the compiler decides that for both overloaded methods it should be a loose method invocation. Further steps are the same as in the case when instead of a ternary conditional expression we use a double value.
From the explanation above it seems that the JLS itself is vague and ambiguous in the part related to conditional expressions when applied to overloaded methods so we had to make some assumptions.
What's interesting is that my IDE (IntelliJ IDEA) doesn't detect the last case (with the ternary conditional expression) as a compiler error. All other cases it detects according to the java compiler from JDK. This means that either JDK java compiler or the internal IDE parser has a bug.
In short:
The compiler doesn't know which method to choose since the ordering between primitive and reference types is not defined in JLS in regards to choosing most specific method.
When you use Integer instead of int the compiler picks the method with Integer because Integer is a subtype of Object.
When you use Double instead of double the compiler picks the method that doesn't involve boxing or unboxing.
Prior to Java 8 the rules were different so this code could compile.

Ambiguous varargs methods

Here's a code example that doesn't compile:
public class Test {
public static void main(String[] args) {
method(1);
}
public static void method(int... x) {
System.out.println("varargs");
}
public static void method(Integer... x) {
System.out.println("single");
}
}
Can someone tell me the reason why these methods are ambiguous ? Thank you in advance.
There are 3 phases used in overload resolution (JLS 15.2.2):
The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.
The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.
The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.
In your example, both methods are variable arity methods, so the third phase applies.
Now, since we have two methods to choose from, we look for the more specific method.
JLS 15.12.2.5. Choosing the Most Specific Method says :
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
...
One applicable method m1 is more specific than another applicable method m2, for an invocation with argument expressions e1, ..., ek, if any of the following are true:
...
m2 is not generic, m1 and m2 are applicable by variable arity invocation, and where the first k variable arity parameter types of m1 are S1, ..., Sk and the first k variable arity parameter types of m2 are T1, ..., Tk, the type Si is more specific than Ti for argument ei for all i (1 ≤ i ≤ k). Additionally, if m2 has k+1 parameters, then the k+1'th variable arity parameter type of m1 is a subtype of the k+1'th variable arity parameter type of m2.
In your case you have two non-generic methods which are applicable by variable arity invocation (i.e. both have varargs). In order for one of the methods to be chosen when you call method(1), one of them has to be more specific than the other. In your case, each method only has one parameter, and for one of them to be more specific than the other, the type of that one parameter must be a subtype of the other method's parameter.
Since int is not a sub-type of Integer and Integer is not a sub-type of int, neither of your methods is more specific than the other. Hence the The method method(int[]) is ambiguous for the type Test error.
An example that would work :
public static void method(Object... x) {
System.out.println("varargs");
}
public static void method(Integer... x) {
System.out.println("single");
}
Since Integer is a sub-type of Object, the second method would be chosen when you call method(1).
Consider the method signatures
public static void foo(int a)
and
public static void foo(Integer a)
Before boxing and unboxing, the call foo(1) would not have been ambiguous. To ensure compatibility with earlier versions of Java, the call remains unambiguous. Therefore the first phase of overload resolution does not allow for boxing, unboxing, or variable arity invocation, which were all introduced at the same time. Variable arity invocation is when you call a varargs method by passing a sequence of parameters for the last argument (rather than an array).
However the resolution of method(1) for your method signatures allows for boxing and unboxing because both methods require a variable arity invocation. Since boxing is allowed, both signatures apply. Normally when two overloadings apply, the most specific overloading is chosen. However neither of your signatures is more specific than the other (because neither int nor Integer is a subtype of the other). Therefore the call method(1) is ambiguous.
You can make this compile by passing new int[]{1} instead.
Because they are ambiguous. According to JLS you can either do widening, boxing or boxing-then-widening. In your example there are 2 methods parameters which can be boxed/unboxed to each other. On compile time though it's not visible because of varargs, which were always not absolutely clear in java.
Even Sun recommended developers not to overload varargs methods, there were bugs in compiler related to it (see here).
The difference between int and Integer is that Integer is an object type.you can use in situation like finding the maximum number of type int , or comparing to integers
Integer object is already associated with methods like compare method:
public static void method(int x, int y) {
System.out.println(Integer.compare(x, y));
}
Find more at : http://docs.oracle.com/javase/7/docs/api/

Compiler error : reference to call ambiguous

Case 1
static void call(Integer i) {
System.out.println("hi" + i);
}
static void call(int i) {
System.out.println("hello" + i);
}
public static void main(String... args) {
call(10);
}
Output of Case 1 : hello10
Case 2
static void call(Integer... i) {
System.out.println("hi" + i);
}
static void call(int... i) {
System.out.println("hello" + i);
}
public static void main(String... args) {
call(10);
}
Shows compilation error reference to call ambiguous. But, I was unable to understand. Why ? But, when I commented out any of the call() methods from Case 2, then It works fine. Can anyone help me to understand, what is happening here ?
Finding the most specific method is defined in a very formal way in the Java Language Specificaion (JLS). I have extracted below the main items that apply while trying to remove the formal formulae as much as possible.
In summary the main items that apply to your questions are:
JLS 15.12.2: your use case falls under phase 3:
The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.
Then JLS 15.12.2.4 basically determines that both method are applicable, because 10 can be converted to both an Integer... or an int.... So far so good. And the paragraph concludes:
The most specific method (§15.12.2.5) is chosen among the applicable variable-arity methods.
Which brings us to JLS 15.12.2.5. This paragraph gives the conditions under which an arity method m(a...) is more specific than another arity method m(b...). In your use case with one parameter and no generics, it boils down to:
m(a...) is more specific than m(b...) iif a <: b, where <: means is a subtype of.
It happens that int is not a subtype of Integer and Integer is not a subtype of int.
To use the JLS language, both call methods are therefore maximally specific (no method is more specific than the other). In this case, the same paragraph concludes:
If all the maximally specific methods have override-equivalent (§8.4.2) signatures [...] => not your case as no generics are involved and Integer and int are different parameters
Otherwise, we say that the method invocation is ambiguous, and a compile-time error occurs.
NOTE
If you replaced Integer... by long... for example, you would have int <: long and the most specific method would be call(int...)*.
Similarly, if you replaced int... by Number..., the call(Integer...) method would be the most specific.
*There was actually a bug in JDKs prior to Java 7 that would show an ambiguous call in that situation.
Looks like it's related to bug #6886431, which seems to be fixed in OpenJDK 7.
Below is the bug description,
Bug Description:
When invoking a method with the following overloaded signatures, I
expect an ambiguity error (assuming the arguments are compatible with
both):
int f(Object... args);
int f(int... args);
javac treats the second as more specific than the first. This
behavior is sensible (I prefer it), but is inconsistent with the JLS
(15.12.2).
from JLS 15.12.2.2
JLS 15.12.2.2 Choose the Most Specific Method
IIf more than one method declaration is both accessible and applicable
to a method invocation, it is necessary to choose one to provide the
descriptor for the run-time method dispatch. The Java programming
language uses the rule that the most specific method is chosen. The
informal intuition is that one method declaration is more specific
than another if any invocation handled by the first method could be
passed on to the other one without a compile-time type error.
neither of these methods can be passed to the other (the types for int[] and Integer[] arent related) hence the call is ambiguous
The compiler doesn't know which method should be called. In order to fix this, you need to cast the input parameters..
public static void main(String... args) {
call((int)10);
call(new Integer(10));
}
EDIT:
It is because the compiler tries to convert the Integer into int, Therefore, an implicit cast takes place prior to invocation of the call method. So the compiler then looks for any methods by that name that can take ints. And you have 2 of them, so the compiler doesn't know which of both should be called.
If more than one method can be applicable, than from the Java Language Specification we Choosing the Most Specific Method, paragraph 15.12.2.5:
One variable arity member method named m is more specific than another variable arity member method of the same name if either (<: means subtyping):
One member method has n parameters and the other has k parameters, where n ≥ k, and:
The types of the parameters of the first member method are T1, ..., Tn-1, Tn[].
(we have only one T_n[], which is Integer[], n=1)
The types of the parameters of the other method are U1, ..., Uk-1, Uk[]. (again only one paramenter, which is int[], k=1)
If the second method is generic then let R1 ... Rp (p ≥ 1) be its type parameters, let Bl be the declared bound of Rl (1 ≤ l ≤ p), let A1 ... Ap be the type arguments inferred (§15.12.2.7) for this invocation under the initial constraints Ti << Ui (1 ≤ i ≤ k-1) and Ti << Uk (k ≤ i ≤ n), and let Si = Ui[R1=A1,...,Rp=Ap] (1 ≤ i ≤ k). (method is not generic)
Otherwise, let Si = Ui (1 ≤ i ≤ k). (S1 = int[])
For all j from 1 to k-1, Tj <: Sj, and, (nothing here)
For all j from k to n, Tj <: Sk, and, (Compare T1 <: S1, Integer[] <: int[])
If the second method is a generic method as described above, then Al <: Bl[R1=A1,...,Rp=Ap] (1 ≤ l ≤ p). (method is not generic)
Although primitive int is autoboxed to wrapper Integer, int[] is not autoboxed to Integer[], than the first condition doesn't hold.
Second condition is almost the same.
There are also other conditions that do not hold, and then due to JLS:
we say that the method invocation is ambiguous, and a compile-time error occurs.
This question has already been asked a number of times. The tricky part is that f(1, 2, 3) is clearly passing int's, so why can't the compiler pick the f(int...) version? The answer must lie somewhere in the JLS, which I'm scratching my heads against
According to §15.12.2.4, both methods are applicable variable-arity method, so the next step is identifying the most specific one.
Unofortunately, §15.12.2.5 uses the subtype test Ti <: Si between f1(T1, .. Tn) and f2(S1, .. Sn) formal parameters to identify the target method, and since there is no subtype relationship between Integer and int, no one wins, because neither int :> Integer nor Integer :> int. At the end of the paragraph is stated:
The above conditions are the only circumstances under which one method
may be more specific than another. [...]
A method m1 is strictly more specific than another method m2 if
and only if m1 is more specific than m2 and m2 is not more specific
than m1.
A method is said to be maximally specific for a method invocation
if it is accessible and applicable and there is no other method that
is applicable and accessible that is strictly more specific.
It is possible that no method is the most specific, because there are
two or more methods that are maximally specific. In this case:
[...]
Otherwise, we say that the method invocation is ambiguous, and a compile-time error occurs.
Attached a blog post by Gilad Bracha (see exhibit 2), in turn linked in the bug report from the #Jayamhona's answer.

Categories

Resources