Java Reference
In-Depth Information
class-name < type-arg-list > var-name = new class-name < >( cons-arg-list );
Here, the type argument list of the new clause is empty.
Although mostly for use in declaration statements, type inference can also be applied to
parameter passing. For example, if the following method is added to TwoGen :
then the following call is legal:
In this case, the type arguments for the arguments passed to isSame( ) can be inferred from
the parameters' types. They don't need to be specified again.
Because the diamond operator was added by JDK 7 and won't work with older com-
pilers, the remaining examples of generics in this topic will continue to use the full syntax
when declaring instances of generic classes. This way, the examples will work with any
Java compiler that supports generics. Using the full-length syntax also makes it very clear
precisely what is being created, which is helpful when example code is shown. Of course,
in your own code, the use of the type inference syntax will streamline your declarations.
Erasure
Usually, it is not necessary for the programmer to know the details about how the Java
compiler transforms your source code into object code. However, in the case of generics,
some general understanding of the process is important because it explains why the generic
features work as they do—and why their behavior is sometimes a bit surprising. For this
reason, a brief discussion of how generics are implemented in Java is in order.
An important constraint that governed the way generics were added to Java was the need
for compatibility with previous versions of Java. Simply put: generic code had to be com-
patible with preexisting, nongeneric code. Thus, any changes to the syntax of the Java lan-
guage, or to the JVM, had to avoid breaking older code. The way Java implements generics
while satisfying this constraint is through the use of erasure .
In general, here is how erasure works. When your Java code is compiled, all generic type
information is removed (erased). This means replacing type parameters with their bound
type, which is Object if no explicit bound is specified, and then applying the appropriate
Search WWH ::




Custom Search