After JDK1.5, if we define a method that takes multiple arguments of the same type, we can simplify it.

Format:

Modifier returns value type method name (parameter type... Parameter name){}Copy the code

Code demo:

public static void main(String[] args) {
    int sum = getSum(6.7.2.12.2121);
    System.out.println(sum);
}

// variable parameters
public static int getSum(int. arr) {
    int sum = 0;
    for (int a : arr) {
    	sum += a;
    }
    return sum;
}
Copy the code

Note:

  • Mutable arguments are essentially arrays.

    • No arguments are passed. The length of the array is 0.
    • You pass a few arguments, and the length of the array is what.
  • There can only be one variable argument in a method.

  • If a method has more than one argument, the variable argument must be written in the last digit.

Eg: Methods for adding elements are also provided in Collections:

public static

boolean addAll(Collection

c, T… Elements: Adds some elements to the collection.

public static void main(String[] args) {
      ArrayList<Integer> list = new ArrayList<Integer>();
      //
      //list.add(12);
      //list.add(14);
      //list.add(15);
      //list.add(1000);
      // Add elements to the collection using the utility class
      Collections.addAll(list, 5.222.1.2);
      System.out.println(list);
}
Copy the code