that is the type of its initializer. Also notice that the use of var results in a shorter
declaration than would be the case otherwise. In general, generic type names can often
be quite long and (in some cases) complicated. The use of var is another way to
substantially shorten such declarations. For the same reasons as just explained for the
diamond operator, the remaining examples in this book will continue to use the full
generic syntax, but in your own code the use of local variable type inference can be
quite helpful.
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 compatible with preexisting, nongeneric code. Thus, any changes to the syntax of the
Java language, 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 casts (as determined by the type arguments) to maintain type compatibility
with the types specified by the type arguments. The compiler also enforces this type
compatibility. This approach to generics means that no type parameters exist at run
time. They are simply a sourcecode mechanism.
AMBIGUITY ERRORS
The inclusion of generics gives rise to a new type of error that you must guard against:
Dostları ilə paylaş: