public class OverloadingVarargsMethodWithNormalMethod {
static void a(int... c){
System.out.println(c.length);
for(int array:c){
System.out.println(array);
}
}
static void a(int d,int e,int f){
System.out.println(d);
System.out.println(e);
System.out.println(f);
}
public static void main(String[] args) {
a(1,2,3);
}
}
我预计会出现不明确的错误。但是,代码运行了第二个“a ”方法。为什么?有两种方法适合 a(1,2,3) 吗?
最佳答案
将调用最具体的函数定义。 int a, int b, int c
比 int... c
更具体。
出于同样的原因,以下内容是有效的
static void foo(String a) {
}
static void foo(Object a) {
}
第一个将被调用 foo("bar");
进一步阅读:https://blogs.oracle.com/mcimadamore/entry/testing_overload_resolution
关于java - Varargs 方法中的重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27697171/