Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
ReturnType1 specific1(primitiveType1... args) { }
ReturnType2 specific2(primitiveType2... args) { }

Noncompliant Code Example

This noncompliant code example shows autoboxing in action when the doSomething method is called with the primitive integer 1 as a parameter (converted to Integer type).

Code Block
bgColor#FFCCCC

doSomething(1)

private void doSomething(Integer... i) {
  System.out.println("autoboxed");
}

Compliant Solution

Be as specific as possible while defining the type of a varargs method to enforce strong compile-time checking.

Code Block
bgColor#ccccff

doSomething(1)

private void doSomething(int... i) { // use int instead of Integer here
  System.out.println("specific");
}

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 may be possible to override the compile-time checking so that with the use of generic varargs, it now compiles cleanly. \[[Bloch 08|AA. Java References#Bloch 08]\]

Also note that autoboxing does not allow strong compile time type checking of primitive types and their corresponding wrapper classes.

Risk Assessment

Unmindful use of the varargs feature breaks strong compile-time type checking, may create ambiguity and diminish code readability.

...