【发布时间】:2016-03-26 08:46:08
【问题描述】:
public class Box<T> {
private T element;
public T getElement() {
return element;
}
public void setElement(T element) {
this.element = element;
}
}
public class Test {
public static void main(String[] args) {
List<Box> l = new ArrayList<>(); //Just List of Box with no specific type
Box<String> box1 = new Box<>();
box1.setElement("aa");
Box<Integer> box2 = new Box<>();
box2.setElement(10);
l.add(box1);
l.add(box2);
//Case 1
Box<Integer> b1 = l.get(0);
System.out.println(b1.getElement()); //why no error
//Case 2
Box<String> b2 = l.get(1);
System.out.println(b2.getElement()); //throws ClassCastException
}
}
列表l 包含Box 类型的元素。在第一种情况下,我将第一个元素作为Box<Integer>,在第二种情况下,列表中的第二个元素作为Box<String> 获得。在第一种情况下不会抛出 ClassCastException。
当我尝试调试时,b1 和 b2 中的 element's 类型分别为 String 和 Integer。
和类型擦除有关吗?
【问题讨论】:
-
我的猜测是
b1在运行时被认为是Box<Object>但这确实是一种奇怪的行为。
标签: java generics type-erasure generic-collections