Person[] persons = new Person[5];//数组中也可以是Person类的子类对象
for(int i = 4; i >= 0; i--){
persons[i] = new Person("P" + i);
}
Person minPerson = getMin(persons);//调用
publicstatic <T extends Comparable> T getMin(T[] a){
......
}
classPersonimplementsComparable{
......
}
例中,getMin方法将返回Object类型,然后将返回的Object类型转换为Person类型。
<2>翻译泛型方法:2>
正常情况直接用限定类型或Object代替T实现擦除
但当遇到类型擦除与多态发生冲突,编译器会生成一个桥方法以支持多态。
4.泛型的约束
<1>不能用基本类型实例化参数,要用其包装类型。(不能用int,用Integer)1>
<2>运行时类型检查只适用于原始类型。2>
无法使用下面的语句检测对象是否为Pair 的实例:
1
2
Pair<String> ps = new Pair<String>();
if(ps instanceof Pair<String>) //ERROR
错误信息:Cannot perform instanceof check against parameterized type Pair. Use the form Pair<?> instead since further generic type information will be erased at runtime