More and more Java libraries are using variable-length parameters that are no longer necessary to add a new object[.
So how do you implement one of these variable-length functions yourself?
Let's do this by adding a long string of integers as an example:
variable length parameter is used t ... It is indicated that in the function body, it is actually an array of type T, and then the variable length parameters like an array of operations are done.
Example:
public class Kmath {public
static int add (int ... args) {int result
= 0;
for (int arg:args) {result
= arg;
}
return result;
}
It should be noted that this t ... You must put it on the last side of the argument list to avoid ambiguity.
Test code:
public class Variablearglengthlisttest {
@Test public
void Test_variable_length_arg_list_works () {
Assertthat (Kmath.add (1, 2, 3, 4), is ());
Assertthat (Kmath.add (1, 2, 3), is (6));
Assertthat (Kmath.add (1, 2), is (3));
Assertthat (Kmath.add (1), is (1));
}
Done.