Java Reference
In-Depth Information
19.17
What happens if lines 12-13 in Listing 19.9 are changed to
public static <T> void add(GenericStack<? extends T> stack1,
GenericStack<T> stack2)
19.8 Erasure and Restrictions on Generics
The information on generics is used by the compiler but is not available at runtime.
This is called type erasure.
Key
Point
Generics are implemented using an approach called type erasure : The compiler uses the
generic type information to compile the code, but erases it afterward. Thus, the generic infor-
mation is not available at runtime. This approach enables the generic code to be backward
compatible with the legacy code that uses raw types.
The generics are present at compile time. Once the compiler confirms that a generic type
is used safely, it converts the generic type to a raw type. For example, the compiler checks
whether the following code in (a) uses generics correctly and then translates it into the equiva-
lent code in (b) for runtime use. The code in (b) uses the raw type.
type erasure
erase generics
ArrayList<String> list = new ArrayList<>();
list.add( "Oklahoma" );
String state = list.get( 0 );
ArrayList list = new ArrayList();
list.add( "Oklahoma" );
String state = (String)(list.get( 0 ));
(b)
(a)
When generic classes, interfaces, and methods are compiled, the compiler replaces the generic
type with the Object type. For example, the compiler would convert the following method
in (a) into (b).
replace generic type
public static <E> void print(E[] list) {
for ( int i = 0 ; i < list.length; i++)
System.out.print(list[i] + " " );
System.out.println();
}
public static void print(Object[] list) {
for ( int i = 0 ; i < list.length; i++)
System.out.print(list[i] + " " );
System.out.println();
}
(a)
(b)
If a generic type is bounded, the compiler replaces it with the bounded type. For example, the
compiler would convert the following method in (a) into (b).
replace bounded type
public static <E extends GeometricObject>
boolean equalArea(
E object1,
E object2) {
return object1.getArea() ==
object2.getArea();
}
public static
boolean equalArea(
GeometricObject object1,
GeometricObject object2) {
return object1.getArea() ==
object2.getArea();
}
(a)
(b)
It is important to note that a generic class is shared by all its instances regardless of its actual
concrete type. Suppose list1 and list2 are created as follows:
important fact
ArrayList<String> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
 
 
 
Search WWH ::




Custom Search