When a method is called, the number of arguments to the method cannot be determined beforehand. For example, the System.out.printf () method has no way of deciding the number of arguments to give beforehand, such as:
?
| 123 |
System.out.printf ("%d", 10); System.out.printf ("%d%d", 10, 20); System.out.printf ("%d%d%d", 10, 20, 30); |
support for variable length parameters (Variable-length Argument) After J2SE 5.0 allows you to easily solve this problem by looking directly at the following example:
?
Mathtool.java
| 123456789 |
public class Mathtool { ; public static int sum (int ... nums) {//use ... Declaration Parameters int sum = 0; for (int num:nums) { Sum + = num; } return sum; }} |
to use the variable length parameter, after the type keyword is declared on the parameter line, you can see in the chunk of the sum () method that, in fact, Nums is an array, the compiler interprets the parameter row (int ... nums) as (int[] nums), You can use the following example to develop parameters of various lengths for the method.
?
Testvarargs.java
| 0102030405060708091011121314 |
public class Testvarargs { public static void main (string[] args ) { int sum = 0; sum = Mathtool.sum (1, 2); system.out.println ("1 + 2 =" + sum); sum = Mathtool.sum (1, 2, 3); system.out.println ("1 + 2 +3 =" + sum); sum = MathTool.sum (1, 2, 3, 4, 5); &Nbsp; system.out.println ("1 + 2 + 3 + 4 + 5 =" + sum); }} |
Execution Result:
1 + 2 = 3
1 + 2 +3 = 6
1 + 2 + 3 + 4 + 5 = 15
The compiler interprets the arguments passed to the method as an int array into sum (), so the function of the indefinite length parameter is also the compilation honey (Compiler Sugar) provided since J2SE 5.0.
When you use an indeterminate length parameter on a method, remember that the parameter that must be declared must be set to the last one in the parameter row. For example, the following method is legal:
?
| 123 |
public void SomeMethod (int arg1, int arg2, int ... varargs) {//...} |
But the following way is not legal:
?
| 123 |
public void SomeMethod (int ... varargs, int arg1, int arg2) {//...} |
It is also not possible to use more than two variable length parameters, for example, the following method is not valid:
?
| 123 |
public void SomeMethod (int ... varargs1, int ... varargs2) {//...} |
If you use an indefinite length parameter for an object, the method is declared the same. For example:
?
| 123 |
public void SomeMethod (SomeClass ... somes) {//...} |
Java variable length parameter