泛型类,听上去很高端的样子,其实只要写过Java代码就无时无刻在和泛型类打交道。
HashMap、List等常用的类便是典型的泛型类。来看下HashMap的定义:
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
{
...
}
K、V便是new HashMap时要具体传入的实际类型,可以是String,也可以是Integer等等。
看一个简单的例子:
/**
* 泛型类
* @version 1.0, 2013-12-9
*/
public class GenericClass<T1, T2> {
private T1 t1;
private T2 t2;
public static void main(String[] args) {
GenericClass<String, Integer> gc = new GenericClass<String, Integer>("papa", 50);
gc.showT1Type();
gc.showT2Type();
}
public GenericClass(T1 t1, T2 t2) {
this.t1 = t1;
this.t2 = t2;
}
public void showT1Type() {
System.out.println("T1:" + t1.getClass().getName());
}
public void showT2Type() {
System.out.println("T2:" + t2.getClass().getName());
}
}
到此基本了解了泛型类,对于深层次的机制可参考:
http://blog.youkuaiyun.com/lonelyroamer/article/details/7868820