Download Free Generics in the Java Programming Language.pdf JDK 1.5 introduces several extensions to the Java programming language. One of these is the introduction of generics. This tutorial is aimed at introducing you to generics. You may be familiar with similar constructs from other languages, most notably C++ templates. If so, you’ll soon see that there are both similarities and important differences. If you are not familiar with look-a-alike constructs from elsewhere, all the better; you can start afresh, without unlearning any misconceptions.

The cast on line 3 is slightly annoying. Typically, the programmer knows what kind of data has been placed into a particular list. However, the cast is essential. The compiler can only guarantee that an Object will be returned by the iterator. To ensure the assignment to a variable of type Integer is type safe, the cast is required. Of course, the cast not only introduces clutter. It also introduces the possibility of a run time error, since the programmer might be mistaken. Now, you might think that all we’ve accomplished is to move the clutter around. Instead of a cast to Integer on line 3, we have Integer as a type parameter on line 1’. However, there is a very big difference here. The compiler can now check the type correctness of the program at compile-time. When we say that myIntList is declared with type List, this tells us something about the variable myIntList, which holds true wherever and whenever it is used, and the compiler will guarantee it. In contrast, the cast tells us something the programmer thinks is true at a single point in the code.

Table contents of Generics in the Java Programming Language
  • Introduction
  • Defining Simple Generics
  • Generics and Subtyping
  • Wildcards
    Bounded Wildcards ~ Generic Methods
  • Interoperating with Legacy Code
    Using Legacy Code in Generic Code ~ Erasure and Translation ~ Using Generic Code in Legacy Code
  • The Fine Print
    Generic Class is Shared by all its Invocations ~ Casts and InstanceOf ~ Arrays
  • Class Literals as Run-time Type Tokens
  • More Fun with Wildcards
  • Converting Legacy Code to Use Generics
  • Acknowledgements