Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java overloading: reference to call ambiguous

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.

like image 813
Entrusc Avatar asked May 19 '16 20:05

Entrusc


1 Answers

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.

like image 174
stdunbar Avatar answered Sep 28 '22 02:09

stdunbar