以下代码无法编译.
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.
}
}
Run Code Online (Sandbox Code Playgroud)
发出编译时错误.
对于测试的引用是不明确的,varargspkg.Main中的方法test(int ...)和varargspkg中的方法test(float ...)匹配
这似乎是显而易见的,因为在方法调用的参数值test(1, 2);可以提升int以及float
如果任何一个或两个参数后缀为F或f,则编译.
但是,如果我们使用相应的包装器类型表示方法签名中的接收参数,如下所示 …
看到这段代码的输出我感到很惊讶:
public class File
{
public static void main(String[] args)
{
movie();
}
static void movie(double... x)
{
System.out.println("No varargs");
}
static void movie(int... x)
{
System.out.println("One argument");
}
}
Run Code Online (Sandbox Code Playgroud)
它输出,
One argument
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
我认为这段代码不能编译,因为调用movie()是模糊的,但运行正常并输出One argument.
如果我将代码修改为:
public class File
{
public static void main(String[] args)
{
movie();
}
static void movie(boolean... x) //Changed the parameter type to boolean from double
{
System.out.println("No varargs");
}
static void movie(int... x)
{
System.out.println("One argument");
}
} …Run Code Online (Sandbox Code Playgroud)