java中的 ...--语法

函数例子

public static double totalTax(Income... incomes) {
        double total = 0;
        for (Income income: incomes) {
            total = total + income.getTax();
        }
        return total;
    }

解释

这个...的意思是可以传入多个参数
在 Java 中,这三个点 ... 被称为 可变参数 (Varargs),全称是 Variable Arguments。
简单来说,它的作用是:允许你在调用方法时,传入任意数量(0个、1个或多个)的参数。

public void printScores(int... scores) { 
    // scores 在方法内部其实被当作一个“数组”来处理
    for (int s : scores) {
        System.out.println(s);
    }
}
printScores();              // 传入 0 个参数,合法
printScores(90);            // 传入 1 个参数,合法
printScores(80, 95, 100);   // 传入 3 个参数,合法
printScores(new int[]{1, 2}); // 直接传入一个数组,也合法

一些规则

如果你在一个方法里混合使用普通参数和可变参数,必须遵守以下两条规则:
必须放在最后:可变参数必须是方法参数列表里的最后一个。
❌ 错误:public void test(int... nums, String name) (编译器不知道哪里结束)
✅ 正确:public void test(String name, int... nums)
只能有一个:一个方法里只能包含一个可变参数。
❌ 错误:public void test(String... s, int... i)

为什么不直接用数组呢

回答是何必呢?

public int sum(int[] numbers) { ... }

// 调用时:你必须手动创建一个数组,哪怕只有一个数字
sum(new int[]{1, 2, 3}); 
sum(new int[]{10});
sum(new int[]{}); // 没数字也要写一长串

一点都不优雅

posted @ 2026-03-31 17:01  Time_q  阅读(8)  评论(0)    收藏  举报