Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java issue with var-args and boxing

Tags:

java

I have a question related to the following code snippet:

    class VarArgsTricky {
    static void wide_vararg(long... x) {
        System.out.println("long...");
    }

    static void wide_vararg(Integer... x) {
        System.out.println("Integer...");
    }

    public static void main(String[] args) {
        int i = 5;
        wide_vararg(i, i, i); // needs to widen and use var-args
        Long l = 9000000000l;
        wide_vararg(l, l); // prints sucessfully "long..."
    }
}

The first call to wide_vararg fails to compile(saying that the method is ambigous) while the second compiles just fine.

Any explanations about this behaviour? Thanks!

like image 807
Ariel Chelsău Avatar asked Oct 02 '11 18:10

Ariel Chelsău


2 Answers

The first wide_vararg call is ambiguous because the compiler could either:

  • widen the ints to longs, and call the first wide_vararg method, or
  • autobox the ints to Integers, and call the second wide_vararg.

It doesn't know which it should do, however, so it refuses to compile the ambiguous method call. If you want the first call to compile, declare i as an Integer or a long, not an int.

like image 104
Matt Ball Avatar answered Nov 12 '22 06:11

Matt Ball


When a var-arg method is invoked, the parameters get converted into an array of that type at compile time.

In the first call, the parameters get converted to an int[]. As all arrays in Java are direct sub types of the Object class, the concept of primitive widening does not apply in which case, both the overloads become equally applicable because long[] and Integer[] are at the same level. Hence the ambiguity

like image 42
Sanjay Bhavnani Avatar answered Nov 12 '22 05:11

Sanjay Bhavnani