Why does this not lead to ambiguity?

I just wrote code with the following structure:

public void method(int x) { //... } public void method(int x, String... things) { //... } 

I was pretty surprised that this compiled, and that if I call

 method(3); 

then he will choose the first. Obviously, in a sense, this is a natural choice, but if the first method does not exist, this would be a reasonable way to call the second (with an empty varargs array). So this should be considered ambiguous and produce a compile-time error?

Or is it considered as a special case?

It seems wrong to consider this as such, because it means that adding a new method can break existing code, and this is not a very happy state of affairs.

("Only good" knows which one you are calling if the first was added as a new subclass method containing the second ...)

+6
source share
2 answers

In accordance with Chapter 15 of the Java Language Specification, the search for an applicable method is carried out in three stages.

The first phase (ยง15.12.2.2) performs overload resolution without allowing box conversion or decompression or using the method call of the arity variable. If no applicable method is found at this stage, processing continues until the second phase.

So, the first method is already applicable in the first phase. The remaining phases are skipped; the String ... method will only be considered in the third phase:

The third phase (ยง15.12.2.4) allows you to combine overloading with the methods of the variable arity, boxing and unpacking.

+10
source

Type argument of the first method:

 int x 

Types of arguments to the second method:

 int x, String[] things 

Therefore, the two methods do not have the same signature, and there is no ambiguity. @Glorfindel explains how Java decides which method to call, but if you want to call the second method without any things , you can pass an empty array.

 method(6, new String[0]); 
0
source

All Articles