代碼:
package test_demo; /* * 可變參數函數說明 * 傳入指定數據類型的數組 * 優先匹配固定長度函數 * */ public class VarArgsDemo { // 可變參數函數 public void printFn(String... args) { for (String s : args) { System.out.print(s + " "); } System.out.println(); } // 優先匹配固定長度函數 public void printFn(String s) { System.out.print("test!\n"); } // 一個固定參數,其它可變參數函數 public void printMore(String str, String... args) { System.out.println(str); for (String s : args) { System.out.print(s + " "); } System.out.println(); } public static void main(String[] args) { VarArgsDemo obj = new VarArgsDemo(); String str = "hello!"; String[] strs = {"hello!", "Good!", "what?"}; // 優先匹配固定長度函數 obj.printFn(str); // 可變參數函數 obj.printFn("hello!", "Good!"); obj.printFn(strs); // 一個固定參數,其它可變參數函數 obj.printMore("------", strs); } }
執行結果:
test! hello! Good! hello! Good! what? ------ hello! Good! what?