Datasheet
Generics are also known as parameterized types where a type is the parameter. As can be seen in the previ-
ous example,
String is the formal type parameter. This same parameterized type must be used when
instantiating the parameterized type.
Because one of the goals of the new language features in Java 5 was to not change the Java instruction
set, generics are, basically, syntactic sugar. When accessing elements of the
ArrayList, the compiler
automatically inserts the casts that you now don’t have to write. It’s also possible to use the primitive
data types as a parameterized type, but realize that these incur boxing/unboxing costs because they are
implicitly converted to and from
Object. Nonetheless, there are benefits in increased type-safety and
increased program readability.
Type Erasure
A generic type in Java is compiled to a single class file. There aren’t separate versions of the generic type
for each formal parameterized type. The implementation of generics utilizes type erasure, which means
the actual parameterized type is reduced to
Object. Strangely, the decision to use erasure, although
requiring no bytecode changes, hobbles the generics mechanism in its determination to maintain strong
typing, as you’ll soon see.
By way of example, the following code will not compile:
interface Shape {
void draw();
}
class Square implements Shape {
public String name;
public Square()
{
name = “Square”;
}
public void draw()
{
System.out.println(“Drawing square”);
}
}
public class ErasureExample {
public static <T> void drawShape(T shape)
{
shape.draw();
}
public static void main(String args[])
{
Square square = new Square();
}
}
8
Part I: Thinking Like a Java Developer
05_777106 ch01.qxp 11/28/06 10:43 PM Page 8