/** * 可變長的參數。 * 有時候,我們傳入到方法的參數的個數是不固定的,為了解決這個問題,我們一般采用下面的方法: * 1. 重載,多重載幾個方法,盡可能的滿足參數的個數。顯然這不是什么好辦法。 * 2. 將參數作為一個數組傳入。雖然這樣我們只需一個方法即可,但是, * 為了傳遞這個數組,我們需要先聲明一個數組,然后將參數一個一個加到數組中。 * 現在,我們可以使用可變長參數解決這個問題, * 也就是使用...將參數聲明成可變長參數。顯然,可變長參數必須是最后一個參數。 */ public class VarArgs { /** * 打印消息,消息數量可以任意多 * @param debug 是否debug模式 * @param msgs 待打印的消息 */ public static void printMsg(boolean debug, String ... msgs){ if (debug){ // 打印消息的長度 System.out.println("DEBUG: 待打印消息的個數為" + msgs.length); } for (String s : msgs){ System.out.println(s); } if (debug){ // 打印消息的長度 System.out.println("DEBUG: 打印消息結束"); } } /** * 重載printMsg方法,將第一個參數類型該為int * @param debugMode 是否debug模式 * @param msgs 待打印的消息 */ public static void printMsg(int debugMode, String ... msgs){ if (debugMode != 0){ // 打印消息的長度 System.out.println("DEBUG: 待打印消息的個數為" + msgs.length); } for (String s : msgs){ System.out.println(s); } if (debugMode != 0){ // 打印消息的長度 System.out.println("DEBUG: 打印消息結束"); } } public static void main(String[] args) { // 調用printMsg(boolean debug, String ... msgs)方法 VarArgs.printMsg(true); VarArgs.printMsg(false, "第一條消息", "這是第二條"); VarArgs.printMsg(true, "第一條", "第二條", "這是第三條"); // 調用printMsg(int debugMode, String ... msgs)方法 VarArgs.printMsg(1, "The first message", "The second message"); } }