JDK1.5新特性(三)……Varargs
援引
Varargs - This facility eliminates the need for manually boxing up argument lists into an array when invoking methods that accept variable-length argument lists.
用法
个数可变的参数
public void foo(int … args){
}
编译器会创建一个数组才存储所有不确定的参数,由于数量不确定,所以可变参数只能有一个,且要放在参数列表末尾
可变参数可传入一个或多个同类型的参数,或者传入一个数组
例子
1: public class VariableParameter {
2:
3: /**
4: * @param args
5: */
6: public static void main(String[] args) {
7: // TODO Auto-generated method stub
8: System.out.println(sum(1, 2, 3));//传入一个
9: System.out.println(sum(1, 2, 3, 4));//传入多个
10: System.out.println(sum(1, 2, new int[] { 3, 4, 5 }));//传入数组
11: }
12: public static int sum(int a,int b,int... arrs){
13: int sum = 0;
14: for(int i : arrs){
15: sum+=i;
16: }
17: return a+b+sum;
18: }
19: }