Java 實例 - 重載(overloading)方法中使用 Varargs
以下實例演示了如何在重載方法中使用可變參數:
Main.java 檔
public class Main {
static void vaTest(int ... no) {
System.out.print("vaTest(int ...): "
+ "參數個數: " + no.length +" 內容: ");
for(int n : no)
System.out.print(n + " ");
System.out.println();
}
static void vaTest(boolean ... bl) {
System.out.print("vaTest(boolean ...) " +
"參數個數: " + bl.length + " 內容: ");
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.length +" 內容: ");
for(int n : no)
System.out.print(n + " ");
System.out.println();
}
public static void main(String args[]){
vaTest(1, 2, 3);
vaTest("測試: ", 10, 20);
vaTest(true, false, false);
}
}
以上代碼運行輸出結果為:
vaTest(int ...): 參數個數: 3 內容: 1 2 3 vaTest(String, int ...): 測試: 參數個數: 2 內容: 10 20 vaTest(boolean ...) 參數個數: 3 內容: true false false