A variable arity call supplies any number of arguments to a final variable arity parameter. Java usually wraps flat arguments into an array, but an explicitly passed array may be used unchanged. section 2.9 section 2.9.1
Flat arguments and explicit arrays
static void printAll(Object... data) { /* ... */ } printAll("Hello", "World"); printAll(new Object[]{"Hello", "World"}); Both calls provide the method with the same array contents. section 2.9.1
A single argument becomes ambiguous when its declared type is Object: even if it holds an array at runtime, compilation wraps it as one element. Passing null is also dangerous because null can be treated as the array reference itself. section 2.9.1 section 2.9.1
Make null intent explicit
printAll((Object)null); // an array containing null printAll((Object[])null); // a null array reference section 2.9.1
Avoid placing a conditional expression directly inside a variable arity call. If one branch is a String and the other an Object[] array, the expression becomes Object and receives an extra array wrapper. section 2.10
Reduce ambiguity with these practices:
- Prefer an if statement over a conditional expression inside a variable arity call. section 2.10
- Cast arguments when you need to distinguish an element from an array reference. section 2.9.1
- Use static-analysis warnings, including IntelliJ IDEA’s Suspicious Ternary Operator in Varargs Method Call inspection, as a review aid. section 2.10
