Java编译器还会擦除泛型方法参数中的类型参数。考虑以下泛型方法:
// Counts the number of occurrences of elem in anArray.
//
public static <T> int count(T[] anArray, T elem) {
int cnt = 0;
for (T e : anArray)
if (e.equals(elem))
++cnt;
return cnt;
}
由于T是无界的,因此Java编译器将其替换为Object:
public static int count(Object[] anArray, Object elem) {
int cnt = 0;
for (Object e : anArray)
if (e.equals(elem))
++cnt;
return cnt;
}
假设定义了以下类:
class Shape { /* ... */ }
class Circle extends Shape { /* ... */ }
class Rectangle extends Shape { /* ... */ }
您可以编写一个泛型方法来绘制不同的形状:
public static <T extends Shape> void draw(T shape) { /* ... */ }
Java编译器替换ŧ为Shape:
public static void draw(Shape shape) { /* ... */ }