Variable parameters
Variable parameters are a method that can receive any number of parameters! For example: fun(), fun(1), fun(1,1), fun(1,1,1). You may think this is a method overload, but this is not an overload. Think about how many methods can be overloaded by overloading, and the fun() method can pass any number of parameters. Can you overload so many methods?
2.1 Defining variable parameter methods
public voidfun(int… arr) {}
The parameter type of the above method fun() is int..., where "..." is not an ellipsis, but a way to define the parameter type. Parameter arr is a variable parameter type. You can understand the above code as: public void fun(int[] arr).
public int sum1(int[] arr) { int sum = 0; for(int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; }public int sum2(int... arr) { int sum = 0; for(int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; }You may think that "int[]" and "int..." are no different, but "int..." is just that "int..." is a new way to define array parameters. Then I should congratulate you! That's right, that's right! But be aware that only int... can be used instead of int[] in the formal parameters of the method.
2.2 Calling methods with variable parameters
Calls to the two methods sum1() and sum2():
sum1(new int[]{1,2,3});sum2(new int[]{1,2,3}); This doesn't look like a difference! But there is another way to call sum2:
sum2();sum2(1);sum2(1,2);sum2(1,2,3);
This looks like using any number of parameters to call the sum2() method, which is the benefit of calling a method with variadic parameters.
2.3 Compiler "secondary processing"
The "secondary processing" result of the compiler's definition of the sum2 method is:
public int sum2(int[] arr) { int sum = 0; for(int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; }That is, modify "int..." to "int[]" type.
The quadratic loading result of the compiler's call to the sum2 method is:
sum2(new int[0]);sum2(new int[] {1});sum2(new int[] {1, 2});sum2(new int[] {1, 2, 3}); Conclusion: Variable parameters are actually array types, but they are more convenient when calling methods. The compiler helps us put multiple real parameters into an array and pass them to formal parameters.
2.4 Limitations of variable parameter methods
l A method can only have one mutable parameter at most;
l The variable parameter must be the last parameter of the method.
The above is the full content of the brief discussion of variable parameters in Java brought to you by the editor. I hope it will be helpful to everyone and support Wulin.com more~