第一个程序验证了擦除;那照理说,第二个也应该擦除,课为什么会有 compile error : incompatible types
错误了?
import java.util.*;
public class ErasedTypeEquivalence {
public static void main(String[] args) {
Class c1 = new ArrayList<String>().getClass();
Class c2 = new ArrayList<Integer>().getClass();
System.out.println(c1 == c2);
}
}
第二个程序:
import java.util.*;
class Fruit
{
}
class Apple extends Fruit
{
}
public class NonCovariantGenerics {
// Compile Error: incompatible types:
List<Fruit> flist = new ArrayList<Apple>();
}
两个都会擦出,只不过第二个在擦除前就报错了。
擦除是在编译后才擦除的,即泛型信息在运行期不可见,所以第一个例子会输出true。
而你的第二个例子报的错是编译期的错误。泛型信息正是在编译期给编译器看的。