...
are placed between the type and the variable name, allowing you to pass any number of arguments without explicitly packing them into an array.At the bytecode level, using an array and a vararg are identical: a vararg parameter
Foo...
is transformed into an array parameter Foo[]
, and at the call site, an implicit instantiation and filling of the array takes place.To avoid ambiguity, varargs have a restriction: there can only be one, and it must be the last argument.
A vararg, like an array, can be empty, which sometimes leads to unexpected behavior. For example, consider two overloaded methods with arguments
int...
and float...
. A call to such a method without parameters will match the version with int
, as it's considered a more specific type. However, having overloads with incompatible types, such as int...
and boolean...
, will result in a compilation error: "Ambiguous method call".When a vararg is of a generic type, a warning "Possible heap pollution from parameterized vararg type" may appear. You need to ensure that you understand the risk, that your code does not cause heap pollution, and inform the compiler of this by using the
@SafeVarargs
annotation.