I saw an argument of ... (3 dots) in the Java source.
java:What...What?
private static void printArgs(String description, Object... args) {
for (Object object : args) {
System.out.println(object);
}
}
Variadic arguments can specify multiple arguments of the specified type.
Try to specify the argument
//This is OK
printArgs("One", "Multiple");
//This is also OK
printArgs("Two", "Multiple", "Designation");
//This is also OK
printArgs("Three", "Multiple", "Designation", true);
//This is OK
printArgs("None");
result
One:Multiple
Two:Multiple designation
Three:Multiple specifications true
None:
Compiling a variadic method produces an array.
After compilation
public void methodName(String description, Object[] vars)
The contents of the method.
}
You can also specify an array as an argument
//This is OK
methodName("Array", new int[]{1,2,3,4,5});
//Even this is OK
methodName("Array and one", new int[]{1,2,3,4,5}, "Multiple");
** Do not overload with an array as an argument ** Reason: It will be the same when compiled
Do not overload with an array as an argument
public void methodName(String description, Object... vars)
The contents of the method.
}
public void methodName(String description, Object[] vars)
The contents of the method.
}
** Variadic argument must be specified at the end ** Reason: Maybe because you don't know how much is the value specified for the variadic argument
Variadic argument must be specified at the end
//I get a compile error in args, and in Eclipse I get this message:(Rough translation:Write the variadic argument at the end)
// 「The variable argument type Object of the method printArgs must be the last parameter」
private static void printArgs2(Object... args, String description) {
The contents of the method.
}
** Only one variable length argument can be specified ** Reason: Maybe you don't know where the first one is, and the first variadic argument isn't specified at the end.
Only one variable length argument can be specified
//I get a compile error in args2, and in Eclipse I get this message:
// 「The variable argument type Object of the method printArgs must be the last parameter」
private static void printArgs2(String description, String... args2, Object... args) {
The contents of the method.
}
//This will not result in a compile error
private static void printArgs2(String description, String[] args2, Object... args) {
The contents of the method.
}
How to test private methods with arrays and variadic arguments in JUnit-Qiita
-Java Variadic Memo (Hishidama's Java VarArgs Memo) -[Java] Precautions when arranging variable-length argument parameters --Qiita
Recommended Posts