Java 可變長參數列表


Java中定義了變長參數,允許在調用方法時傳入不定長度的參數。

定義及調用

在定義方法時,在最后一個形參后加上三點 …,就表示該形參可以接受多個參數值,多個參數值被當成數組傳入。上述定義有幾個要點需要注意:

  • 可變參數只能作為函數的最后一個參數,但其前面可以有也可以沒有任何其他參數

  • 由於可變參數必須是最后一個參數,所以一個函數最多只能有一個可變參數

  • Java的可變參數,會被編譯器轉型為一個數組

  • 變長參數在編譯為字節碼后,在方法簽名中就是以數組形態出現的。這兩個方法的簽名是一致的,不能作為方法的重載。如果同時出現,是不能編譯通過的。可變參數可以兼容數組,反之則不成立

public void foo(String...varargs){}

foo("arg1", "arg2", "arg3");

//上述過程和下面的調用是等價的
foo(new String[]{"arg1", "arg2", "arg3"});

例如,求任意個整數的乘積。

package exercise;

public class product {
    public static int func(int... args){
        int ret = 1;
        for(int i:args)  ret *= i;
        return ret;
    }
    public static void main(String[] args){
        System.out.println(func(1,2,3));
        System.out.println(func(2,2,2,2,2,2));
        System.out.println(func(100,1000));
    }
}

由於可變長參數就是被編譯器轉化為數組實現的,我們完全可以寫成以數組做參數的形式:

package exercise;

public class product {
    public static int func(int[] args){
        int ret = 1;
        for(int i:args)  ret *= i;
        return ret;
    }
    public static void main(String[] args){
        System.out.println(func(new int[]{1,2,3}));
        System.out.println(func(new int[]{2,2,2,2,2,2}));
        System.out.println(func(new int[]{100,1000}));
    }
}

方法重載

優先匹配固定參數

調用一個被重載的方法時,如果此調用既能夠和固定參數的重載方法匹配,也能夠與可變長參數的重載方法匹配,則選擇固定參數的方法:

public class Varargs {

    public static void test(String... args) {
        System.out.println("version 1");
    }

    public static void test(String arg1, String arg2) {
        System.out.println("version 2");
    }
    public static void main(String[] args) {
        test("a","b");     //version 2 優先匹配固定參數的重載方法
                test();    //version 1
    }
}

匹配多個可變參數

調用一個被重載的方法時,如果此調用既能夠和兩個可變長參數的重載方法匹配,則編譯出錯:

public class Varargs {

    public static void test(String... args) {
        System.out.println("version 1");
    }

    public static void test(String arg1, String... arg2) {
        System.out.println("version 2");
    }
    public static void main(String[] args) {
        test("a","b");  //Compile error
    }
}

 

 

參考鏈接:http://www.runoob.com/w3cnote/java-varargs-parameter.html

 


免責聲明!

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



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