JDK 1.5 引入 varargs(型別... 參數名),允許方法接受 0 至多個同型別參數,編譯器自動轉為陣列。解決過去需撰寫大量重載方法或改用陣列/集合的困擾。
修飾字 回傳型別 方法名(固定參數列表, 型別... 參數名) { ... }
... 必須是三個點,緊接在型別後for (型別 e : 參數名))void printInvitation(String... names) {
for (String name : names) {
makeCard(name);
System.out.println("Recording info: invitation card has been printed for " + name);
}
}
// 呼叫
printInvitation("李剛", "David Smith");
printInvitation("Greg Wu", "Paul Nguyen", "Liu Wei", "張新");
printInvitation(); // 無參數,不執行迴圈
public static int sumInts(int... numbers) {
int sum = 0;
for (int num : numbers) sum += num;
return sum;
}
public void totalTax(String name, double rate, double... amounts) {
double total = 0;
for (double amt : amounts) total += amt;
double tax = total * rate;
System.out.println("Name: " + name + "\nTotal: " + total + "\nTax: " + tax);
}
public class Supper {
public Supper(char... characters) { ... }
}
class SubClass extends Supper {
public SubClass(char... characters) { ... } // 可覆寫
// 無法用 super(char...) 呼叫父類別建構子
}
可變參數方法可正常重載,遵循一般重載規則(參數型別/數量不同):
void someMethod(int count, double... prices) { ... }
void someMethod(double... prices) { ... } // 重載
double someMethod(String... names) { ... } // 重載
enum ColorType {
WHITE { String getDescription() { return "有淺白、暗白、和亮白可選"; } },
SILVER { String getDescription() { return "有銀白、銀灰、純銀色可選"; } },
BLACK { String getDescription() { return "有深黑和淺黑可選"; } };
abstract String getDescription();
}
enum PaymentType {
CASH("有10%特別優惠"), CREDIT("接受所有信用卡"), LOAN("貸款利息為.56%");
final private String payment;
PaymentType(String p) { payment = p; }
public String getPayment() { return payment; }
}
class SportCar {
SportCarType type; ColorType color; PaymentType payment;
public SportCar(String... choices) { // 可變參數
processInfo(choices);
}
private void processInfo(String[] choices) {
if (choices.length == 1) processType(choices[0]);
else if (choices.length == 2) { processType(choices[0]); processColor(choices[1]); }
else if (choices.length == 3) { processType(choices[0]); processColor(choices[1]); processPayment(choices[2]); }
}
// processType, processColor, processPayment 解析字串設定列舉值
// toString() 格式化輸出
}
public class VarargsApp {
public static void main(String[] args) {
SportCar yourCar = new SportCar("P"); // 保時捷
SportCar myCar = new SportCar("J", "S"); // 捷豹 + 銀色
SportCar herCar = new SportCar("F", "B", "C"); // 法拉利 + 黑色 + 現金
System.out.println("你要的跑車資訊:\n" + yourCar);
System.out.println("我要的跑車資訊:\n" + myCar);
System.out.println("她要的跑車資訊:\n" + herCar);
}
}
輸出:
你要的跑車資訊: 製造國:德國 價格:$120,000.00 我要的跑車資訊: 製造國:英國 價格:$110,000.00 有銀白、銀灰、純銀色可選 她要的跑車資訊: 製造國: 義大利 價格:$150,000.00 有深黑和淺黑可選 有10%特別優惠
foo(int...) vs foo(Integer...))null 會導致 NPE,建議檢查 if (args == null || args.length == 0)可變參數大幅簡化 API 設計,配合列舉、重載、建構子等特性,能撰寫出靈活且可讀性高的程式碼。掌握其語法規則與陣列本質,善用於參數數量不固定的場景(如格式化、聚合計算、建構器選項)。