The following is a simple applet:
1 import java.util.Arrays;2 3 classLesson64 {5 Public Static voidMain (string[] args)6 {7 intarray[]={2,3,1,5,4,6};8System. out. println (arrays.tostring (array));9System. out. println (getsum (array));Ten //System.out.println (Getsum (2,3,1,5,4,6)); One } A - Static intGetsum (intArray[])//Sum of the calculated elements - { the intsum=0; - for(intI=0; i<array.length;i++) -sum+=Array[i]; - returnsum; + } -}View Code
Where the declaration of the getsum (int array[]) method qualifies it to accept only one-dimensional array of type int. If we now try to run line tenth (the line that is commented on), it will definitely go wrong. This method is declared in particular when it is not known to pass in the number of parameters, the shortcomings are obvious.
Starting with JAVA5, variable parameters are present. Features: variable number of parameters, you can pass 0 to N, must be the last parameter of the method, when the method of the variable parameter is called, the compiler implicitly creates an array for the variable parameter, and accesses the variable parameter in the form of an array in the method body.
We cancel the comment of the above code and change getsum (int array[]) to getsum (int ... array) to achieve the result we want. The results are as follows:
From the bottom two times output 21 is available, getsum (int ... array) successfully received 2 different numbers of incoming.
In addition, one thing that needs special attention in practical programming is that the variable parameter must be the last parameter of the method. You can experiment with simple changes to the above code.
"Java Basics" mutable parameters