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!
The first wide_vararg
call is ambiguous because the compiler could either:
int
s to long
s, and call the first wide_vararg
method, or
int
s to Integer
s, 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
.
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
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