JDK 1.5 开始,Java支持传递同类型的可变参数给一个方法。一个方法中只能指定一个可变参数,它必须是方法的最后一个参数。任何普通的参数必须在它之前声明。
声明方式:
返回值类型 方法名称(类型 参数一, 类型 参数二, 类型...参数三) {
//方法体;
}
类型...参数; 必须是方法的最后一个参数,其他的参数必须在它之前声明。
1:可以传递数组:
public class overLoadTest {
public static void main(String[] args) {
overLoad firstLoad = new overLoad();
firstLoad.show(0, new int[]{10, 20, 30, 40});
}
}
class overLoad {
public void show(int num ,int...array) {
for (int i = 0; i < array.length; i ++) {
System.out.println(array[i]);
}
}
}
2:可以用逗号分隔:
public class overLoadTest {
public static void main(String[] args) {
overLoad firstLoad = new overLoad();
firstLoad.show(0, 10, 20, 30, 40);
}
}
class overLoad {
public void show(int num ,int...array) {
for (int i = 0; i < array.length; i ++) {
System.out.println(array[i]);
}
}
}
在这里的0是给num的
3:不写参数,传入空的:
public class overLoadTest {
public static void main(String[] args) {
overLoad firstLoad = new overLoad();
firstLoad.show();
}
}
class overLoad {
public void show(int...array) {
for (int i = 0; i < array.length; i ++) {
System.out.println(array[i]);
}
System.out.println("啥也没有啊");
}
}
总结一些,个人理解,传进去的可变参数就是一个数组,那么传进去的就可以是很多个数字,也可以直接传进去数组,也可以传进去的是空数组。
all in all
传入空参;
可以直接在里边写入参数,用逗号隔开;
传入一个数组;