method(1); // This works -
void method(int... x) { }
void method(int x) { } // - this method is called
If I add a varargs parameter to the second method, I get a "reference to method is ambiguous" compilation error:
method(1); // This now fails
void method(int... x) { }
void method(int x, String... y) { } // adding String... y causes a problem.
As the String... y argument(s) can be left "blank", why doesn't Java still pick that method? Thanks, and apologies if there is a closely matching explanation on SO; I did look for one.
The compiler always makes the choice to use the most specific method.
In the first case, because the number of the arguments exactly matches void method(int x)
, it is the one that's being called.
In the second case, the number of the arguments don't match any case, and it can be called from both methods, resulting the ambiguity.
Check the JLS - 15.12.2. Compile-Time Step 2: Determine Method Signature for details.
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