The Java compiler type-checks the arguments to each varargs method to ensure that the arguments are of the same type or object reference. However, the compile-time checking is ineffective when Object
or generic T
parameter types are used [Bloch 2008]. Another (Note that it does not matter if there are initial parameters of specific types, the compiler will still not be able to check Object
or generic T
vararg parameter types.) A requirement for providing strong compile-time type checking of variable argument methods is to be as specific as possible when declaring the type of the method parameter.
...
Code Block | ||
---|---|---|
| ||
Collection<T> assembleCollection(T... args) { Collection<T> result = new HashSet<T>(); // add each argument to the result collection return result; } |
DCL60-EX1: In some circumstances, it is necessary to use a vararg parameter of type Object
. A good example of this is the method java.util.Formatter.format(String format, Object... args)
which can format objects of any type.
Risk Assessment
Injudicious use of varargs parameter types prevents strong compile-time type checking, creates ambiguity, and diminishes code readability.
...