Variable parameters in Java
Java adds a new feature: variable parameters: this feature is applicable to situations where the number of parameters is uncertain and the type is determined. java treats variable parameters as arrays.
Features:
1. It can only appear at the end of the parameter list;
2. The ellipsis (...) is located between the variable type and the variable name. It can be preceded by spaces.
3. When the variable parameter method is called, the compiler implicitly creates an array for the variable parameter,
Access variable parameters in the form of arrays in the method body
Program example:
Public class Test {// evaluate the public void add (int x, int... arr) // variable parameter {int sum = x; // first copy the value of the first parameter to sumfor (int I = 0; I <arr. length; ++ I) {sum + = arr [I];} System. out. println (sum);} public static void main (String [] args) {// TODO Auto-generated method stubTest tt = new Test (); tt. add (2); // The sum is 2. The variable parameter length can be 0 tt. add (2, 3); // and 5tt. add (2, 3, 4, 5); // The sum is 14tt. add (2, 3, 4, 5, 6, 7 );}}
Usage of variable-length parameters in java
Easy to write code ..
For example, public void method (int... a) {} is an int array in this method body ..
But if it is written as public void method (int [] .. When using this method .. You must upload the array ..
You can change the parameter to method (1, 2, 3. You do not need to use mehotd (new int [] {1, 2, 3 }).. You can also upload an array .. Convenient
How does one define variable parameters in java?
Method overload,
Syntax:
Access modifier (public) method type (void, etc.) method name (parameter 1, parameter 21 ·) {method subject}
The method type and method name are consistent. The corresponding method is automatically selected based on different parameter types and numbers.
Please adopt it!