类型擦除
无论何时定义一个泛型类型,都自动提供了一个相应的原始类型(raw type)。原始类型的名字就是删除类型参数后的泛型类型名(如果限定的类型变量有多个 参考例2,则用第一个限定的类型变量替换)。擦除(erased)类型变量,并替换为限定类型(无限定的变量用Object)
例1:
无限定情况:
//泛型
public class Pair<T>{
private T first;
private T second;
public T getFirst() {
return first;
}
public void setFirst(T first) {
this.first = first;
}
public T getSecond() {
return second;
}
public void setSecond(T second) {
this.second = second;
}
}
//类型擦除
public class Pair<Object>{
private Object first;
private Object second;
public Object getFirst() {
return first;
}
public void setFirst(Object first) {
this.first = first;
}
public Object getSecond() {
return second;
}
public void setSecond(Object second) {
this.second = second;
}
}
例2:具有相应原始类型
//泛型
class Interval<T extends Comparable & Serializable> implements Serializable{
private T lower;
private T upper;
public T getLower() {
return lower;
}
public void setLower(T lower) {
this.lower = lower;
}
public T getUpper() {
return upper;
}
public void setUpper(T upper) {
this.upper = upper;
}
}
//类型擦除
class Interval implements Serializable{
private Comparable lower;
private Comparable upper;
public Comparable getLower() {
return lower;
}
public void setLower(Comparable lower) {
this.lower = lower;
}
public Comparable getUpper() {
return upper;
}
public void setUpper(Comparable upper) {
this.upper = upper;
}
}