泛型类
import java.util.List;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
A<String> a1 = new A<String>();//在new A的对象是制定了A的数据类型String
a1.setKey("xxx");//对象使用setKey(T key)方法中的key形参就是String类型
String a= a1.getKey();//T getKey(),返回值就由new对象确定时String
A<Integer> a2 = new A<Integer>();
a2.setKey(1);
Integer i = a2.getKey();
A a3 = new A();//不指定,则为Object类型
a3.setKey(new Object());
//同样的类,但是在new对象时泛型使用不同的数据类型,这些对象不能相互赋值
// a2 = a1;
}
}
/**
* 此处泛型T可以任意取名(一般大写):Type
*/
class A<T>{
private T key;
public void setKey(T key) {
this.key = key;
}
public T getKey() {
return this.key;
}
}