Reputation: 357
Consider the following example code:
public class TestClass {
public void doSth(String str, String l, Object... objects) {
System.out.println("A");
}
public void doSth(String str, Object... objects) {
System.out.println("B");
}
}
When I now call new TestClass().doSth("foo", "bar")
I get the expected result A
. But if I change the method signature of the first method by chaging the parameter l
to a primitive type:
public class TestClass {
public void doSth(String str, long l, Object... objects) {
System.out.println("A");
}
public void doSth(String str, Object... objects) {
System.out.println("B");
}
}
calling new TestClass().doSth("foo", 2L)
will yield a reference to call ambiguous
compile time error.
I thought about that one for some time now and also consulted this stackoverflow question, but I was unable to understand why this happens. In my opinion the doSth("foo", 2L)
is more specific to the doSth(String string, long l, Object... obj)
signature and should allow the compiler to also come to this conclusion.
Upvotes: 12
Views: 713
Reputation: 20185
At this state, I can only report my observation, not the exact argumentation as to WHY Java behaves, like it does.
First, changing the methods to
void doSth(long l) {...}
void doSth(Object o) {...}
gets rid of the problem, i.e. doSth(2L);
will yield the expected result.
Going one step further, changing the method parameter to varargs
void doSth(long... ls) {...}
void doSth(Object... os) {...}
together with the call doSth(2l);
yields the same compilation error as reported by OP.
My suggestion at this stage is that encapusalting the parameter into an array, together with Autoboxing causes the havoc. My knowledge about the JLS is not firm enough to explain this properly.
Upvotes: 1
Reputation: 17455
In this case, auto-boxing is causing you grief. Ironically, before that you're correct - the "long" version would have easily been picked.
Basically the compiler knows that it can create a Long from your value which, of course, is an Object. So it is still confused as either the long or the Long version could be used. Is one "better" than the other? Maybe but it is a pretty fine line.
Upvotes: 5