当把一个带有泛型信息的变量赋值给一个不带泛型信息的变量时,泛型信息将被擦除,对元素的类型参数检查将变成类型的上限。
class Apple<T extends Number>{
T size;
public Apple(){
}
public T getSize() {
return size;
}
public void setSize(T size) {
this.size = size;
}
}
public class ErasureTest {
public static void main(String[] args) {
Apple<Integer> ap=new Apple<>();
Integer apSize=ap.getSize();
Apple ap2=ap;
//Type mismatch: cannot convert from Number to Integer
//Integer apSize2=ap2.getSize();
}
}理论上,List<string>是List的子类,把List对象直接赋给List<string>应该出现编译错误,但实际上不会。</string></string>
public class ErasureTest2 {
public static void main(String[] args) {
List<Integer> li = new ArrayList<>();
li.add(1);
// 泛型擦除
List list = li;
System.out.println(li.get(0));
// 警告:The expression of type List needs unchecked conversion to conform
// to
List<String> ls = list;
// Exception :java.lang.Integer cannot be cast to java.lang.String
System.out.println(ls.get(0));
}
}
京公网安备 11010502036488号