传递的参数不确定长度,是变长的参数,例如小例子:
package demo;
public class Demo {
public static int sum(int n, int... nums) {
for (int i = 0; i < nums.length; i++) {
n = n + nums[i];
}
return n;
}
public static void main(String[] args) {
int s1 = sum(1, 2);
int s2 = sum(1, 2, 3);
int s3 = sum(1, 2, 3, 4);
int s4 = sum(1, 2, 3, 4, 5);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
}
}
运行结果:
3
6
10
15
注意:必须把变长参数作为最后一个参数传递过去。