Java定義方法可變參數


眾所周知, Java可以通過... 來給一個方法定義一個可變長度的參數.
例如

// 返回可變參數的個數
public void method(int ... i){
      System.out.println(i.length);
}

其中注意點一共有兩個

  1. 只能設定一個可變參數, 並且這個參數必須在最后
//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);
}

以上兩種都是錯誤的使用方式

  1. 調用的時候, 可以省略這個可變參數. 也就是說, 可以設定最后一個參數的個數為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});

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM