java可变参数
多个数相加
1、只含有一个可变参数
public class Test { private static int getSum(int...arr){ int sum = 0; for(int param : arr){ sum+=param; } return sum; } public static void main(String[] args) { //0个数相加 int zeroParam = getSum(); System.out.println(zeroParam); //2个数相加 int twoParam = getSum(5,6); System.out.println(twoParam); //数组求和 int[] array = new int[8]; array[0] = 0; array[1] = 1; array[2] = 2; array[3] = 3; array[4] = 4; array[5] = 5; array[6] = 6; array[7] = 7; int arrayParam = getSum(array); System.out.println(arrayParam); } }
2、多个参数
public class Test { private static int getSum(int a,int...arr){ int sum = a; for(int param : arr){ sum+=param; } return sum; } public static void main(String[] args) { //0个数相加 int zeroParam = getSum(1); System.out.println(zeroParam); //2个数相加 int twoParam = getSum(1,5,6); System.out.println(twoParam); //数组求和 int[] array = new int[8]; array[0] = 0; array[1] = 1; array[2] = 2; array[3] = 3; array[4] = 4; array[5] = 5; array[6] = 6; array[7] = 7; int arrayParam = getSum(1,array); System.out.println(arrayParam); } }
可变参注意事项
1、一个方法中只能存在一个可变参数
2、可变参数必须放到最后一个参数位置