Please, could you help me to understand why compilation of first call of testVargArgsAutoboxingPriority fails?
In case of second call compiler is able to select proper method by preferring primitive (first parameter) to Object but after varargs parameter addition compiler is not able to make the selection any more.
Fail message is
\jdk1.6.0_45\bin\javac.exe ocjp6/AutoBoxingOldStyleVarargsPriority.java
ocjp6\AutoBoxingOldStyleVarargsPriority.java:7: reference to testVargArgsAutoboxingPriority is ambiguous, both method testVargArgsAutoboxing
Priority(java.lang.Integer,boolean...) in ocjp6.AutoBoxingOldStyleVarargsPriority and method testVargArgsAutoboxingPriority(int,boolean...)
in ocjp6.AutoBoxingOldStyleVarargsPriority match
testVargArgsAutoboxingPriority( 5, true ); // the line compilation fails
^
1 error
Full code listing is
package ocjp6;
public class AutoBoxingOldStyleVarargsPriority
{
public static void main( final String[] args )
{
testVargArgsAutoboxingPriority( 5, true ); // the line compilation fails
testVargArgsAutoboxingPriority( 5 );
}
private static void testVargArgsAutoboxingPriority( Integer b, boolean... c )
{}
private static void testVargArgsAutoboxingPriority( int b, boolean... c )
{}
private static void testVargArgsAutoboxingPriority( Integer b )
{}
private static void testVargArgsAutoboxingPriority( int b )
{}
}
As per JLS 15.12.2 Compile-Time Step 2: Determine Method Signature.
The answer lies in the JLS - 15.12.2. Compile-Time Step 2: Determine Method Signature and on @TheNewIdiot answer above. Here is a more detailed explanation:
For the methods:
The compiler needs only the first phase in order to know which method to call. And in the first phase it's not mixing boxed and primitive types.
But the methods:
contains varargs arguments and the compiler needs to get to the third phase trying to distinguish between them. But in the third phase is not able anymore to make the distinction between a boxed type and its corresponding primitive type.