The following code doesn't compile.
package varargspkg;
public class Main {
public static void test(int... i) {
for (int t = 0; t < i.length; t++) {
System.out.println(i[t]);
}
System.out.println("int");
}
public static void test(float... f) {
for (int t = 0; t < f.length; t++) {
System.out.println(f[t]);
}
System.out.println("float");
}
public static void main(String[] args) {
test(1, 2); //Compilation error here quoted as follows.
}
}
A compile-time error is issued.
reference to test is ambiguous, both method test(int...) in varargspkg.Main and method test(float...) in varargspkg.Main match
It seems to be obvious because the parameter values in the method call test(1, 2);
can be promoted to int
as well as float
If anyone or both of the parameters are suffixed by F
or f
, it compiles.
If we however, represent the receiving parameters in the method signature with respective wrapper types as follows
public static void test(Integer... i) {
System.out.println("Integer" + Arrays.asList(i));
}
public static void test(Float... f) {
System.out.println("Float" + Arrays.asList(f));
}
then the call to the method test(1, 2);
doesn't issue any compilation error. The method to be invoked in this case is the one that accepts one Integer
varargs parameter (the first one in the preceding snippet).
Why is in this case the error as in the first case not reported? It appears that auto-boxing and automatic type promotion are both applied here. Is auto-boxing applied first so that the error is resolved?
The Oracle docs says,
Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.
The last sentence in this link. It's however for the sake of better understanding varargs.
Also to add below code compiles just fine.
public class OverLoading {
public static void main(String[] args) {
load(1);
}
public static void load(int i) {
System.out.println("int");
}
public static void load(float i) {
System.out.println("float");
}
}
EDIT:
The following is the snap shot that indicates the compilation error. I have created a new application therefore the package name is different.
I'm using JDK 6.