Datasheet

The compiler issues the following error:
ErasureExample.java:23: cannot find symbol
symbol : method draw()
location: class java.lang.Object
shape.draw();
^
1 error
If you replace the drawShape method with the following, the compiler is now happy to compile the
program:
public static <T> void drawShape(T shape)
{
System.out.println(“Hashcode: “ + shape.hashCode());
}
Why this discrepancy? It’s the result of type erasure. The hashCode method belongs to Object, how-
ever the draw method belongs only to objects of type
Shape. This little experiment demonstrates that
the parameterized type is actually reduced to an
Object. The next example shows how this relates to
use of a generic class with different parameterized types.
Start with a new generic class to hold a data item of arbitrary type:
public class CustomHolder<E>
{
E storedItem;
public E getItem()
{
return(storedItem);
}
public void putItem(E item)
{
System.out.println(“Adding data of type “ + item.getClass().getName());
storedItem = item;
}
}
By convention, single letters are used for formal type parameters, usually E for element and T for type.
Add a main method to this class:
public static void main(String args[])
{
CustomHolder<String> stringHolder = new CustomHolder<String>();
CustomHolder<Object> objectHolder = new CustomHolder<Object>();
String str = new String(“test string”);
String str2;
stringHolder.putItem(str);
9
Chapter 1: Key Java Language Features and Libraries
05_777106 ch01.qxp 11/28/06 10:43 PM Page 9