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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With