Can Arguments Be Passed as an Array to a Method with Variable Arguments in Java?
Consider the following desired function:
class A { private String extraVar; public String myFormat(String format, Object ... args) { return String.format(format, extraVar, args); } }
In this scenario, args is interpreted as Object[] within the myFormat method, resulting in a single argument being provided to String.format. However, the aim is to have each Object in args passed as a distinct argument.
Is It Possible?
Yes, it is possible since T... is merely syntactic sugar for T[].
Java Language Specification (JLS) 8.4.1 defines:
The last formal parameter in a list is special; it may be a variable arity parameter, indicated by an elipsis following the type.
If the last formal parameter is a variable arity parameter of type T, it is considered to define a formal parameter of type T[].
Example Illustrating Variable Arity Parameter:
public static String ezFormat(Object... args) { String format = new String(new char[args.length]) .replace("<pre class="brush:php;toolbar:false">static void count(Object... objs) { System.out.println(objs.length); } count(null, null, null); // prints "3" count(null, null); // prints "2" count(null); // throws NullPointerException!!!
In the main method, args is a String[], which is passed to ezFormat. The method treats it as Object[] because of covariance.
Varargs Gotchas:
Passing null
int[] myNumbers = { 1, 2, 3 }; System.out.println(ezFormat(myNumbers)); // prints "[ [I@13c5982 ]"
To work around this, call with Object[] { null } or (Object) null.
Adding Extra Arguments to an Array
To pass an array of primitive types, wrap it in a reference array:
Integer[] myNumbers = { 1, 2, 3 }; System.out.println(ezFormat(myNumbers)); // prints "[ 1 ][ 2 ][ 3 ]"
The above is the detailed content of Can Java Methods with Variable Arguments Accept an Array as Multiple Arguments?. For more information, please follow other related articles on the PHP Chinese website!