Versions Compared

Key

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

Wiki Markup
            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 \[java:[Bloch 2008|AA. References#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.

...

This noncompliant code example declares a vararg method using Object. It accepts an arbitrary mix of parameters of any object type. Legitimate uses of such declarations are rare. (See exception below"Exceptions").

Code Block
bgColor#FFCCCC
ReturnType method(Object... args) { }

...

Wiki Markup
Retrofitting old methods containing final array parameters with generically- typed varargs is not always a good idea. For example, given a method that does not accept an argument of a particular type, it could be possible to override the compile-time checking --- through the use of generic varargs parameters --- so that the method would compile cleanly rather than correctly, causing a compile-time error \[java:[Bloch 2008|AA. References#Bloch 08]\]. 

...

DCL03-EX0: Varargs signatures using Object and imprecise generic types are acceptable when the body of the method does not use casts or auto-boxing autoboxing 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;
}

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="12f861c48e1e875c-877ca76d-455b4feb-ae578993-84257e216f786f39ef7e9817"><ac:plain-text-body><![CDATA[

[java:[Bloch 2008

AA. References#Bloch 08]]

Item 42: "Use Varargs Judiciously"

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="06554e58b046c1aa-6e6af7c9-4e2e4ecb-a2308fdc-6c31d7321ad507512afa393c"><ac:plain-text-body><![CDATA[

[java:[Steinberg 2005

AA. References#Steinberg 05]]

"Using the Varargs Language Feature"

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="732a3c2cfcc6903d-bd262e0a-48f04fba-aad98084-8f7c54bf9d21d3684e0d8a56"><ac:plain-text-body><![CDATA[

[java:[Sun 2006

AA. References#Sun 06]]

[varargs

http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html]

]]></ac:plain-text-body></ac:structured-macro>

...