Java Reference
In-Depth Information
For versions of Java prior to JDK 7, to create an instance of TwoGen , you must use a state-
ment similar to the following:
Here, the type arguments (which are Integer and String ) are specified twice: first, when
tgOb is declared, and second, when a TwoGen instance is created via new . Since generics
were introduced by JDK 5, this is the form required by all versions of Java prior to JDK 7.
While there is nothing wrong, per se, with this form, it is a bit more verbose than it needs
to be. Since, in the new clause, the type of the type arguments can be readily inferred, there
is really no reason that they need to be specified a second time. To address this situation,
JDK 7 added a syntactic element that lets you avoid the second specification.
Beginning with JDK 7, the preceding declaration can be rewritten as shown here:
Notice that the instance creation portion simply uses < >, which is an empty type argument
list. This is referred to as the diamond operator. It tells the compiler to infer the type ar-
guments needed by the constructor in the new expression. The principal advantage of this
type-inference syntax is that it shortens what are sometimes quite long declaration state-
ments. This is especially helpful for generic types that specify bounds.
The preceding example can be generalized. When type inference is used, the declaration
syntax for a generic reference and instance creation has this general form:
Search WWH ::




Custom Search