java不定参数(可变参数)
package variableParams;
public class VariableParams {
public static void main(String[] args) {
method(1);
method();
method(1,2,3,4,5,6);//可以直接写参数
int[] a = {1, 2, 3, 4, 5, 6, 7};
method(a);//可以传数组
}
public static void method(int... args) {
//不定参数本质上是一个数组,可以调用数组方法
int length = args.length;
System.out.println("------>不定参数方法正在运行<-------");
int i = 0;
for (int e : args) {
i++;
}
System.out.println("参数长度为:" + length);
System.out.println("参数个数为:" + i);
}
public static void method(int i) {
System.out.println("------>单个参数方法正在运行<-------");
}
public static void method(int i, int j) {
System.out.println("------>两个参数方法正在运行<-------");
}
public static void method1(int[] arr) {
System.out.println("......");
}
// public static void method(int[] args) {
// //编译时报Duplicate method method(int[]) in type VariableParams,
// //不能使用数组实现不定参数方法重载,不定参数本质上是一个数组
//
// }
// public static void method(int i, int...args) {
// //编译时时报The method method(int[]) is ambiguous for the type VariableParams
// //务必保证参数列表不一致
// }
// private static void method(int... args,int... params) {
// //编译时报The variable argument type int of the method method must be the last parameter
// // 不定参数项只能在最后,所以只能有一个
//
// }
}