擦除失去了在泛型代码中执行某些操作的能力,任何在运行时需要知道确切类型信息的操作都将无法工作,看下面的例子:
public class Eras<T>{
public static void main(String[] args){
if(ages instanceof T){}//出错
T var = new T(); //出错
T[] array =new T[100];//出错
}
}
在例子中使用instanceof失败,因为它的类型已经被擦除了。
不能创建泛型数组,
如果想创建泛型数组,使用ArrayList,
public class ListOfGenerics<T>{
private List<T> array = new ArrayList<T>();
public void add(T item){
array.add(item);
}
public T get(int idnex){
retrun array.get(index);
}
}
即使创建了数组
Dog<Integer>[] dog;
在编译器是没有问题的,但是在运行期仍然是个Object类型。
解决办法:
不能创建T[] array = new T[sz];,可创建一个对象数组,将其转型
public class A{
private T[] array;
public A(int size){
array = (T[])new Object[size];
}
}
class Fruit {}
class Apple extends Fruit {}
class Jonathan extends Apple {}
class Orange extends Fruit {}
public class CovariantArrays {
public static void main(String[] args) {
Fruit[] fruit = new Apple[10];
fruit[0] = new Apple(); // OK
fruit[1] = new Jonathan(); // OK
// Runtime type is Apple[], not Fruit[] or Orange[]:
try {
// Compiler allows you to add Fruit:
fruit[0] = new Fruit(); // ArrayStoreException
} catch(Exception e) { System.out.println(e); }
try {
// Compiler allows you to add Oranges:
fruit[0] = new Orange(); // ArrayStoreException
} catch(Exception e) { System.out.println(e); }
}
} /* Output:
java.lang.ArrayStoreException: Fruit
java.lang.ArrayStoreException: Orange
编译器允许放入Fruit对象,但这在运行时处理的却是Apple[]类型,错误就发生了,ArrayStoreException