找回密码
 立即注册
首页 业界区 业界 Java方法之可变个数形参(Varargs)学习笔记 ...

Java方法之可变个数形参(Varargs)学习笔记

向梦桐 昨天 10:50
使用场景

在调用方法时,可能会出现形参的类型是确定的,但是形参的个数是不确定的。此时,使用可变个数形参的方法。
格式

(参数类型... 参数名)
说明


  • 可变个数形参方法的调用,针对形参的赋值个数,可以为:0个、1个或多个。
  • 可变个数的形参方法在同一个类中,同名的多个方法之间可以构成方法的重载(类型相同的数组不构成重载)
  • 可变个数的形参在一个方法的形参列表中只出现一次,且必须声明在形参列表的最后
代码范例

基础使用示例
  1. public class VarargsExample {
  2.    
  3.     // 1. 基本可变参数方法
  4.     public static void printNumbers(int... numbers) {
  5.         System.out.println("接收到的数字个数: " + numbers.length);
  6.         for (int num : numbers) {
  7.             System.out.print(num + " ");
  8.         }
  9.         System.out.println();
  10.     }
  11.    
  12.     // 2. 可变参数与固定参数结合
  13.     public static void printMessageWithNumbers(String message, int... numbers) {
  14.         System.out.print(message + ": ");
  15.         for (int num : numbers) {
  16.             System.out.print(num + " ");
  17.         }
  18.         System.out.println();
  19.     }
  20.    
  21.     // 3. 零个参数的情况
  22.     public static void demonstrateZeroArgs() {
  23.         printNumbers(); // 不传递任何参数
  24.         printMessageWithNumbers("没有数字"); // 只传递固定参数
  25.     }
  26.    
  27.     // 4. 方法重载示例
  28.     public static void processData(String... strings) {
  29.         System.out.println("处理字符串数据: " + String.join(", ", strings));
  30.     }
  31.    
  32.     public static void processData(int... numbers) {
  33.         System.out.println("处理数字数据: " + Arrays.toString(numbers));
  34.     }
  35.    
  36.     // 5. 与数组参数的区别(不能构成重载)
  37.     // 以下两个方法不能同时存在,因为编译后会冲突
  38.     // public static void conflictExample(String... strs) {}
  39.     // public static void conflictExample(String[] strs) {} // 编译错误
  40. }
复制代码
实际应用场景示例
  1. public class PracticalExamples {
  2.    
  3.     // 场景1: 日志记录 - 可以接受任意数量的日志参数
  4.     public static void log(String level, String... messages) {
  5.         String timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME);
  6.         System.out.println("[" + timestamp + "] [" + level + "] " + String.join(" ", messages));
  7.     }
  8.    
  9.     // 场景2: 数学计算 - 计算多个数字的和
  10.     public static double sum(double... numbers) {
  11.         double total = 0;
  12.         for (double num : numbers) {
  13.             total += num;
  14.         }
  15.         return total;
  16.     }
  17.    
  18.     // 场景3: 字符串处理 - 连接多个字符串
  19.     public static String concatenate(String delimiter, String... strings) {
  20.         return String.join(delimiter, strings);
  21.     }
  22.    
  23.     // 场景4: 参数验证 - 检查多个条件
  24.     public static void validateArguments(String name, int age, String... requirements) {
  25.         if (name == null || name.trim().isEmpty()) {
  26.             throw new IllegalArgumentException("姓名不能为空");
  27.         }
  28.         if (age < 0 || age > 150) {
  29.             throw new IllegalArgumentException("年龄无效");
  30.         }
  31.         for (String req : requirements) {
  32.             if (req == null || req.trim().isEmpty()) {
  33.                 throw new IllegalArgumentException("要求参数不能为空");
  34.             }
  35.         }
  36.     }
  37. }
复制代码
测试类展示各种调用方式
  1. public class VarargsTest {
  2.     public static void main(String[] args) {
  3.         
  4.         // 1. 不同数量的参数调用
  5.         PracticalExamples.log("INFO", "系统启动成功");
  6.         PracticalExamples.log("DEBUG", "用户登录", "用户ID: 123", "时间: 2024-01-01");
  7.         PracticalExamples.log("ERROR", "数据库连接失败", "重试次数: 3");
  8.         
  9.         // 2. 数学计算示例
  10.         System.out.println("和1: " + PracticalExamples.sum()); // 0个参数
  11.         System.out.println("和2: " + PracticalExamples.sum(5)); // 1个参数
  12.         System.out.println("和3: " + PracticalExamples.sum(1, 2, 3, 4, 5)); // 多个参数
  13.         
  14.         // 3. 字符串连接示例
  15.         String result1 = PracticalExamples.concatenate(", ", "Java", "Python", "C++");
  16.         String result2 = PracticalExamples.concatenate(" - ", "开始", "进行中", "结束");
  17.         System.out.println("连接结果1: " + result1);
  18.         System.out.println("连接结果2: " + result2);
  19.         
  20.         // 4. 参数验证
  21.         PracticalExamples.validateArguments("张三", 25, "必须有邮箱", "必须有手机号");
  22.         
  23.         // 5. 方法重载调用
  24.         VarargsExample.processData("Hello", "World");
  25.         VarargsExample.processData(1, 2, 3, 4);
  26.         
  27.         // 6. 数组传递给可变参数
  28.         int[] numbers = {10, 20, 30};
  29.         VarargsExample.printNumbers(numbers); // 可以直接传递数组
  30.         
  31.         String[] messages = {"消息1", "消息2", "消息3"};
  32.         PracticalExamples.log("INFO", messages); // 数组作为可变参数
  33.     }
  34. }
复制代码
输出结果示例
  1. [14:30:25.123] [INFO] 系统启动成功
  2. [14:30:25.124] [DEBUG] 用户登录 用户ID: 123 时间: 2024-01-01
  3. [14:30:25.125] [ERROR] 数据库连接失败 重试次数: 3
  4. 和1: 0.0
  5. 和2: 5.0
  6. 和3: 15.0
  7. 连接结果1: Java, Python, C++
  8. 连接结果2: 开始 - 进行中 - 结束
  9. 处理字符串数据: Hello, World
  10. 处理数字数据: [1, 2, 3, 4]
  11. 接收到的数字个数: 3
  12. 10 20 30
  13. [14:30:25.126] [INFO] 消息1 消息2 消息3
复制代码
注意事项


  • 只能有一个可变参数:一个方法中只能有一个可变参数
  • 必须在最后:可变参数必须是方法的最后一个参数
  • 性能考虑:频繁调用时,每次都会创建新数组,可能影响性能
  • 与重载的配合:要小心设计重载方法,避免调用歧义
这些范例展示了可变参数在实际开发中的常见应用场景,帮助理解其灵活性和便利性。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册