泛型实现了参数化类型的概念,使代码可以应用于多种类型。
- 简单泛型
public class Hold{ private T a; public Hold(T a){ this.a = a; } public T getA() { return a; } public void setA(T a) { this.a = a; } }
- 泛型接口
public interface Generator{ T test(); }
- 泛型方法
public class Hold{
public void f(T a){
System.out.println(a.getClass().getName());
}
}
2.泛型的擦除
考点:在泛型代码内部,无法获得任何有关泛型参数类型的信息。
- 考题1
class c1 = new ArrayList().getClass();
class c2 = new ArrayList().getClass();
System.out.println(c1 == c2);
答案:true
- 考题2
class Frob {}
class Fnorkle {}
class Quark {}
class Particle {}
public class LostInformation {
public static void main(String[] args) {
List list = new ArrayList();
Map map = new HashMap();
Quark quark = new Quark();
Particle p = new Particle();
System.out.println(Arrays.toString(
list.getClass().getTypeParameters()));
System.out.println(Arrays.toString(
map.getClass().getTypeParameters()));
System.out.println(Arrays.toString(
quark.getClass().getTypeParameters()));
System.out.println(Arrays.toString(
p.getClass().getTypeParameters()));
}
}
//:~
3.泛型的边界
将某个参数限制为某个类型的子集。为了执行这种限制,Java 泛型重用了extends 关键字。
interface HasColor { java.awt.Color getColor(); }
class Colored {
T item;
Colored(T item) { this.item = item; }
T getItem() { return item; }
// The bound allows you to call a method:
java.awt.Color color() { return item.getColor(); }
}



