Erasure at Compilation Time

When the compiler translates generic method printArray into Java bytecodes, it removes the type-parameter section and replaces the type parameters with actual types. This process is known as erasure. By default all generic types are replaced with type Object. So the compiled version of method printArray appears as shown in Fig. 20.4—there’s only one copy of this code, which is used for all printArray calls in the example. This is quite different from similar mechanisms in other programming languages, such as C++’s templates, in which a separate copy of the source code is generated and compiled for every type passed as an argument to the method. As you’ll see in Section 20.4, the translation and compilation of generics ...

Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.