Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: mitotically split code samples

Wiki Markup
The Java compiler type-checks the arguments to a varargs method to ensure that they are of the same type or object reference. However, the compile-time checking is ineffective when two method signatures are used in particular—{{Object}} and the generic type {{T}} \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. Another 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.

Noncompliant Code Example (Object)

This noncompliant code example declares two varargs methods. As written, the first a vararg method using Object. It accepts an arbitrary mix of parameters of any object type; the second accepts a variable number of parameters that are all of the same object type. Although such declarations have legitimate uses (see exception below), those uses rarely arise; avoid use of such declarations in general.

Code Block
bgColor#FFCCCC
ReturnType1ReturnType suspect1function(Object... args) { }
<T> ReturnType2

Noncompliant Code Example (generic type)

This noncompliant code example declares a vararg method using a generic type parameter. It accepts a variable number of parameters that are all of the same object type. Again, although such declarations have legitimate uses, those uses rarely arise.

Code Block
bgColor#FFCCCC

<T> ReturnType function suspect2(T... args) { }

Compliant Solution

Be as specific as possible when declaring parameter types; avoid Object and imprecise generic types in varargs.

Code Block
bgColor#ccccff
ReturnType1ReturnType specific1(somePrimitiveType1... args) { } // int, or whatever
ReturnType2 specific2(SpecificObjectType2function(SpecificObjectType... args) { }

Wiki Markup
Retrofitting old methods containing final array parameters with generically-typed varargs is not always a good idea. This is because, if some method did not accept an argument of a particular type, it could be possible to override the compile-time checking so that, with the use of generic varargs, it now compiles cleanly \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. 

...

DCL09-EX1: Varargs signatures using Object and imprecise generic types are only acceptable when, and only when , the body of the method uses no casts or auto-boxing, and compiles without error. Consider the following example:, which operates correctly for all object types and type-checks successfully.

Code Block
bgColor#ccccff
Collection<T> assembleCollection(T... args) {
  Collection<T> result = new HashSet<T>();
  // add each argument to the result collection
  return result;
}

...

Risk Assessment

Unmindful use of the varargs feature breaks strong compile-time type checking, creates ambiguity, and diminishes code readability.

...