因为类型擦除的问题,所有的泛型类型变量最后都会被替换为原始类型。
既然都被替换为原始类型,那么为什么我们在获取的时候,不需要进行强制类型转换呢?
看下ArrayList.get()
方法:
public E get(int index) {
RangeCheck(index);
return (E) elementData[index];
}
可以看到,在return
之前,会根据泛型变量进行强转。假设泛型类型变量为Date
,虽然泛型信息会被擦除掉,但是会将(E) elementData[index]
,编译为(Date)elementData[index]
。所以我们不用自己进行强转。当存取一个泛型域时也会自动插入强制类型转换。假设Pair
类的value
域是public
的,那么表达式:
Date date = pair.value;
也会自动地在结果字节码中插入强制类型转换。