1.泛型的历史?
从JDK1.5之后,Java的Class类增加了泛型功能,从而允许使用泛型来限制Class类,例如,String.class实际上是Class<String>,如果将Class对应的类暂时设置成未知, 则使用Class<?>
2.什么是泛型?
JDK1.5之后,使用泛型来接受类中要操作的引用数据类型(类,接口,数组)。
3.什么时候用泛型?
当类中要操作的引用数据类型不确定的时候,就是用泛型来表示。
4.泛型的好处?
通过在反射中使用泛型,可以避免使用反射生成的对象需要强制类型装换,如果不使用泛型,可能发生ClassCastException。
5./**
* 将泛型定义在方法上。
* @param str
*/
public <W> void show(W str){
System.out.println("show : "+str.toString());
}
public void print(QQ str){
System.out.println("print : "+str);
}
/**
* 当方法静态时,不能访问类上定义的泛型。如果静态方法使用泛型,
* 只能将泛型定义在方法上。
* @param obj
*/
public static <Y> void method(Y obj){
System.out.println("method:"+obj);
}
6.public class GenericDefineDemo5 {
/**
* @param args
*/
public static void main(String[] args) {
InterImpl in = new InterImpl();
in.show("abc");
InterImpl2<Integer> in2 = new InterImpl2<Integer>();
in2.show(5);
}
}
//泛型接口,将泛型定义在接口上。
interface Inter<T>{
public void show(T t);
}
class InterImpl2<Q> implements Inter<Q>{
public void show(Q q){
System.out.println("show :"+q);
}
}
class InterImpl implements Inter<String>{
public void show(String str){
System.out.println("show :"+str);
}
}