To better understand how erasure works, consider the following two classes:
// Here, T is bound by Object by default.
class Gen<T> {
T ob; // here, T will be replaced by Object
Gen(T o) {
ob = o;
}
// Return ob.
T getob() {
return ob;
}
}
// Here, T is bound by String.
class GenStr<T extends String> {
T str; // here, T will be replaced by String
GenStr(T o) {
str = o;
}
T getstr() { return str; }
}
After these two classes are compiled, theTinGenwill be replaced byObject. TheTin
GenStrwill be replaced byString. You can confirm this by runningjavapon their compiled
classes. The results are shown here:
class Gen extends java.lang.Object{
java.lang.Object ob;
Gen(java.lang.Object);
java.lang.Object getob();
}
class GenStr extends java.lang.Object{
java.lang.String str;
GenStr(java.lang.String);
java.lang.String getstr();
}
Within the code forGenandGenStr, casts are employed to ensure proper typing. For
example, this sequence:
Gen<Integer> iOb = new Gen<Integer>(99);
int x = iOb.getob();
would be compiled as if it were written like this:
350 Part I: The Java Language