J2SE 1.5 includes "varargs" support. In general this causes
autoboxing of varargs arguments into an Object[]. However
there are some special cases where if a single varargs argument
is passed then it is passed verbatim. (This is necessary for
backwards compatibility.)
This is potentially confusing to developers who may expect
that all varargs arguments will always be auto-boxed.
For exmaple, if you pass a single varargs argument of type null
or of type String[] then the value doesn't get boxed.
See a small test case below. This generates the output:
"none" x0 { }
"1" 1 { 1 }
"null" null
"array of two strings" 2 { one two }
This indicates that the first two calls on doStuff are getting
boxed into arrays, but in the third and fourth calls the exact
arguments is being passed without boxing.
public class VarArgs {
static java.io.PrintStream out = System.out;
private static void doStuff(String mess, Object... args) {
out.printf("\"%s\"", mess);
if (args == null) {
out.printf(" null\n");
return;
}
out.printf(" %d {", args.length);
for (Object arg: args) {
out.printf(" %s", arg);
}
out.printf(" }\n");
}
public static void main(String argv[]) {
doStuff("none"); // Boxing occurs OK.
doStuff("1", 1); // Boxing occurs OK.
doStuff("null", null); // No boxing occurs.
String strings[] = { "one", "two" };
doStuff("array of two strings", strings); // No boxing occurs
}
}
As suggested by Neal, the right answer seems to be to provide
a compiler warning for the problematic cases.
###@###.### 2004-03-31
- duplicates
-
JDK-4969664 (fmt) Formatter fails to throw exception for String array
- Closed
-
JDK-5017888 [need warn] Varargs behaviour is inconsistent when called with a single null
- Closed