可變參數的特點:
1. 在變量類型之后用 "..." 來聲明該變量為可變的,"..." 位于變量類型和變量名之間,中間有無空格都行
2. 只能出現在參數列表的最后,作為最后一個參數傳遞到方法中
3. 可變參數相當于一個長度不確定的數組,在方法體中可以以數組的形式來訪問可變參數
For a simple example:
public class TestApp {
public static void main(String[] args){
System.out.println(add(1,2,3));
System.out.println(add(1,2,3,4,5));
}
private static int add(int ... args){
int sum = 0;
for(int index : args){
sum += index;
}
return sum;
}
}
posted on 2012-08-24 11:02
fancydeepin 閱讀(761)
評論(0) 編輯 收藏