可变参数方法

56 阅读1分钟

在java中, 如果我们需要定义一个方法, 该方法可以接收任意多个同类型的参数,那么这种方法我们就叫做 可变参数方法, 可变参数其底层其实就是一个数组, 使用 数据类型... 变量名 来定义

定义可变参数的方法示例如下

public class Demo {
    public static void main(String[] args) {
      int s = sum(1, 2, 3);
      System.out.println(s);
    }
    
    public static int sum(int... arr) { // 可变参数
      int sum = 0;
      for (int a : arr) {
        sum += a;
      }
      return sum;
    }
}

jdk中使用可变参数的示例

在jdk中, Collections集合工具类中有一个addAll方法,其底层就使用到了可变参数

public class Demo {
   public static void main(String[] args) {
      ArrayList<String> list = new ArrayList<>();
      Collections.addAll(list, "hello", "world");
      System.out.println(list); // 打印 [hello, world]
    }
}

image.png

定义可变参数方法需要注意的两点

  1. 一个方法只能有一个可变参数
  2. 如果方法有多个参数, 可变参数要放到形参列表的最后
public class Demo {

    public static void main(String[] args) {
        int i = 1;
        int j = 2;
        test1(i,j);
    }
    
    public static void test1(int... a) { // IDE显示正常,语法正确
        for (int i:a) {
            System.out.println(i);
        }
    }

    // 注意点1: 一个方法只能有一个可变参数
    public static void test2(int... a, int... b) { // IDE提示报错: Vararg parameter must be the last in the list 
        for (int i:a) {
            System.out.println(i);
        }
    }
    public static void test3(int... b, int... a) { // IDE提示报错: Vararg parameter must be the last in the list 
        for (int i:a) {
            System.out.println(i);
        }
    }
    
    // 注意点2: 如果方法有多个参数, 可变参数要放到形参列表的最后
    public static void test4(int... a, int b) { // IDE提示报错: Vararg parameter must be the last in the list 
        for (int i:a) {
            System.out.println(i);
        }
    }
    public static void test4(int b, int... a) { // IDE显示正常,语法正确
        for (int i:a) {
            System.out.println(i);
        }
    }
    
}