java可变参数重载问题
public class Test_Demo {
static void f(float i, Character... s) {
System.out.println("first");
System.out.println(i);
for(Character c :s){
System.out.println(c);
}
}
static void f(Character... s) {
System.out.println("second");
}
public static void main(String[] args) {
f(1, 'a');
f('a', 'b');
}
}
会报错 Exception in thread "main"
java.lang.Error: Unresolved compilation problem:
The method f(float, Character[]) is ambiguous for the type Test_Demo
at com.test.Test_Demo.main(Test_Demo.java:19)
但是改成
public class Test_Demo {
static void f(float i, Character... s) {
System.out.println("first");
System.out.println(i);
for(Character c :s){
System.out.println(c);
}
}
static void f(char c ,Character... s) {
System.out.println("second");
}
public static void main(String[] args) {
f(1, 'a');
f('a', 'b');
}
}
后就没有问题了 我最大的疑问就是 f(char c ,Character... s) 与 f(Character...s)的区别 为什么添加了一个char c的形参就不报错了
------解决方案--------------------嗯,你说的对。
我又参考3L的写法,做了个小例子:
static void f(char c, Character... s)
{
System.out.println("mohu1");
}
static void f(char c,char c2, Character... s)
{
System.out.println("mohu1");
}
public static void main(String[] args)
{
f('a', 'b');
}