眾所周知, Java可以通過... 來給一個方法定義一個可變長度的參數.
例如
// 返回可變參數的個數
public void method(int ... i){
System.out.println(i.length);
}
其中注意點一共有兩個
- 只能設定一個可變參數, 並且這個參數必須在最后
//Vararg parameter must be the last in the list
public void method(int... i, String str){
System.out.println(i.length);
}
//Vararg parameter must be the last in the list
public void method(int... i, String... str){
System.out.println(i.length);
}
以上兩種都是錯誤的使用方式
- 調用的時候, 可以省略這個可變參數. 也就是說, 可以設定最后一個參數的個數為0.
public void test(String str, int... i){
System.out.println(str);
}
public static void main(String[] args) {
System.out.println();
//no error
new Sample().test("hello");
}
順便說一下, 一個對象即使調用了這個方法, 在調用時個數也是模糊的.
public void test(String str, int... i){
System.out.println(str);
}
public static void main(String[] args) {
System.out.println();
Sample sample = new Sample();
sample.test("as",new int[]{1,2});
sample.test("as",new int[]{1,2,3});
}