Java可變長度引數過載?

2019-10-16 22:30:31

在Java中,在處理方法過載時如何使用可變引數作為輸入?

此範例演示如何過載具有可變引數作為輸入的方法。

package com.yiibai;

public class UseVarargsMethodOverloading {
    static void vaTest(int... no) {
        System.out.print("vaTest(int ...): " + "Number of args: " + no.length
                + " Contents: ");
        for (int n : no)
            System.out.print(n + " ");
        System.out.println();
    }

    static void vaTest(boolean... bl) {
        System.out.print("vaTest(boolean ...) " + "Number of args: "
                + bl.length + " Contents: ");
        for (boolean b : bl)
            System.out.print(b + " ");
        System.out.println();
    }

    static void vaTest(String msg, int... no) {
        System.out.print("vaTest(String, int ...): " + msg
                + "no. of arguments: " + no.length + " Contents: ");
        for (int n : no)
            System.out.print(n + " ");
        System.out.println();
    }

    public static void main(String args[]) {
        vaTest(1, 2, 3);
        vaTest("Testing: ", 10, 20);
        vaTest(true, false, false);
    }
}

執行上面範例程式碼,得到以下結果 -

vaTest(int ...): Number of args: 3 Contents: 1 2 3 
vaTest(String, int ...): Testing: no. of arguments: 2 Contents: 10 20 
vaTest(boolean ...) Number of args: 3 Contents: true false false

範例-2

以下是具有方法過載的可變引數的另一個範例。

package com.yiibai;

public class UseVarargsMethodOverloading2 {
    static void vararg(Integer... x) {
        System.out.println("Integer...");
    }

    static void vararg(String... x) {
        System.out.println("String...");
    }

    public static void main(String[] args) {
        int i = 0;
        vararg(i, i);
        String s = "";
        vararg(s, s);
    }
}

執行上面範例程式碼,得到以下結果 -

Integer...
String...