使用场景
在调用方法时,可能会出现形参的类型是确定的,但是形参的个数是不确定的。此时,使用可变个数形参的方法。
格式
(参数类型... 参数名)
说明
- 可变个数形参方法的调用,针对形参的赋值个数,可以为:0个、1个或多个。
- 可变个数的形参方法在同一个类中,同名的多个方法之间可以构成方法的重载(类型相同的数组不构成重载)
- 可变个数的形参在一个方法的形参列表中只出现一次,且必须声明在形参列表的最后
代码范例
基础使用示例
- public class VarargsExample {
-
- // 1. 基本可变参数方法
- public static void printNumbers(int... numbers) {
- System.out.println("接收到的数字个数: " + numbers.length);
- for (int num : numbers) {
- System.out.print(num + " ");
- }
- System.out.println();
- }
-
- // 2. 可变参数与固定参数结合
- public static void printMessageWithNumbers(String message, int... numbers) {
- System.out.print(message + ": ");
- for (int num : numbers) {
- System.out.print(num + " ");
- }
- System.out.println();
- }
-
- // 3. 零个参数的情况
- public static void demonstrateZeroArgs() {
- printNumbers(); // 不传递任何参数
- printMessageWithNumbers("没有数字"); // 只传递固定参数
- }
-
- // 4. 方法重载示例
- public static void processData(String... strings) {
- System.out.println("处理字符串数据: " + String.join(", ", strings));
- }
-
- public static void processData(int... numbers) {
- System.out.println("处理数字数据: " + Arrays.toString(numbers));
- }
-
- // 5. 与数组参数的区别(不能构成重载)
- // 以下两个方法不能同时存在,因为编译后会冲突
- // public static void conflictExample(String... strs) {}
- // public static void conflictExample(String[] strs) {} // 编译错误
- }
复制代码 实际应用场景示例
- public class PracticalExamples {
-
- // 场景1: 日志记录 - 可以接受任意数量的日志参数
- public static void log(String level, String... messages) {
- String timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME);
- System.out.println("[" + timestamp + "] [" + level + "] " + String.join(" ", messages));
- }
-
- // 场景2: 数学计算 - 计算多个数字的和
- public static double sum(double... numbers) {
- double total = 0;
- for (double num : numbers) {
- total += num;
- }
- return total;
- }
-
- // 场景3: 字符串处理 - 连接多个字符串
- public static String concatenate(String delimiter, String... strings) {
- return String.join(delimiter, strings);
- }
-
- // 场景4: 参数验证 - 检查多个条件
- public static void validateArguments(String name, int age, String... requirements) {
- if (name == null || name.trim().isEmpty()) {
- throw new IllegalArgumentException("姓名不能为空");
- }
- if (age < 0 || age > 150) {
- throw new IllegalArgumentException("年龄无效");
- }
- for (String req : requirements) {
- if (req == null || req.trim().isEmpty()) {
- throw new IllegalArgumentException("要求参数不能为空");
- }
- }
- }
- }
复制代码 测试类展示各种调用方式
- public class VarargsTest {
- public static void main(String[] args) {
-
- // 1. 不同数量的参数调用
- PracticalExamples.log("INFO", "系统启动成功");
- PracticalExamples.log("DEBUG", "用户登录", "用户ID: 123", "时间: 2024-01-01");
- PracticalExamples.log("ERROR", "数据库连接失败", "重试次数: 3");
-
- // 2. 数学计算示例
- System.out.println("和1: " + PracticalExamples.sum()); // 0个参数
- System.out.println("和2: " + PracticalExamples.sum(5)); // 1个参数
- System.out.println("和3: " + PracticalExamples.sum(1, 2, 3, 4, 5)); // 多个参数
-
- // 3. 字符串连接示例
- String result1 = PracticalExamples.concatenate(", ", "Java", "Python", "C++");
- String result2 = PracticalExamples.concatenate(" - ", "开始", "进行中", "结束");
- System.out.println("连接结果1: " + result1);
- System.out.println("连接结果2: " + result2);
-
- // 4. 参数验证
- PracticalExamples.validateArguments("张三", 25, "必须有邮箱", "必须有手机号");
-
- // 5. 方法重载调用
- VarargsExample.processData("Hello", "World");
- VarargsExample.processData(1, 2, 3, 4);
-
- // 6. 数组传递给可变参数
- int[] numbers = {10, 20, 30};
- VarargsExample.printNumbers(numbers); // 可以直接传递数组
-
- String[] messages = {"消息1", "消息2", "消息3"};
- PracticalExamples.log("INFO", messages); // 数组作为可变参数
- }
- }
复制代码 输出结果示例
- [14:30:25.123] [INFO] 系统启动成功
- [14:30:25.124] [DEBUG] 用户登录 用户ID: 123 时间: 2024-01-01
- [14:30:25.125] [ERROR] 数据库连接失败 重试次数: 3
- 和1: 0.0
- 和2: 5.0
- 和3: 15.0
- 连接结果1: Java, Python, C++
- 连接结果2: 开始 - 进行中 - 结束
- 处理字符串数据: Hello, World
- 处理数字数据: [1, 2, 3, 4]
- 接收到的数字个数: 3
- 10 20 30
- [14:30:25.126] [INFO] 消息1 消息2 消息3
复制代码 注意事项
- 只能有一个可变参数:一个方法中只能有一个可变参数
- 必须在最后:可变参数必须是方法的最后一个参数
- 性能考虑:频繁调用时,每次都会创建新数组,可能影响性能
- 与重载的配合:要小心设计重载方法,避免调用歧义
这些范例展示了可变参数在实际开发中的常见应用场景,帮助理解其灵活性和便利性。
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |