泛型
泛型提供了编译时类型安全检测机制,程序员可以在编译过程中发现非法的类型,泛型的本质是参数化类型,即数据类型作为一个参数
泛型方法
单参数泛型方法示例如下:
public static <E> void say(E arg){
System.out.println(arg);
}
//泛型方法有<E>修饰,<E>是类型参数说明,表示该方法是泛型方法,接受的参数类型是E
//这部分在返回值类型(void)前面
多参数泛型方法示例如下:
public static <E,V> void say(E arg,V arg2){
if (arg instanceof Integer){
System.out.println("Integer" + arg);
}
if (arg instanceof String ){
System.out.println("String" + arg);
}
if (arg2 instanceof Integer){
System.out.println("Integer" + arg2);
}
if (arg2 instanceof String ){
System.out.println("String" + arg2);
}
}
//<E,V>在多参数泛型方法中,类型参数说明可以有多个参数
//每个参数之间用逗号隔开,同时在函数说明中的形参个数和格式也必须与之匹配
返回参数泛型方法示例如下:
public static <E> E say(E arg){
return arg;
}
//<E>表示该方法是一个泛型方法
//E表示该方法返回的类型是E
//泛型参数又叫类型变量只能是引用类型,不能是基本类型
//8种基本类型int,float,double,long,short,byte,char,boolean
泛型类
public class date<T,V> {
private T d;
private V c;
date()
{
}
public T getD() {
return d;
}
public void setD(T d) {
this.d = d;
}
public V getC() {
return c;
}
public void setC(V c) {
this.c = c;
}
public <T> T getDate(Class<T> t){
return t.newInstance();
}
}
上面例子可以看出:
- 泛型类和泛型方法的声明相似,都是需要定义泛型参数
- 泛型类的泛型参数在类名后面,泛型方法的泛型参数在返回值类型前面
- 多参数泛型类原理与多参数的泛型方法类似,泛型参数之间用逗号隔开
通过反射获取泛型类对象
date d = new date();
d.getDate(Class.forName("example.zjl.com.generic.date"));//使用反射创建类对象
通配符
?代表通配符,List表示元素格式是String的列表,List<?>表示元素格式可以是任何格式的列表。List<?>逻辑上是List<具体类型>的父类
public class Generic {
public static void main(String [] args){
List<Integer> integerList = new ArrayList<Integer>();
List<String > stringList = new ArrayList<String>();
List<Number> numberList = new ArrayList<Number>();
integerList.add(1);
stringList.add("string");
numberList.add(1);
say(integerList);
say(stringList);
say(numberList);
}
public static void say(List<?> list){
System.out.println(list.get(0));
}
}
上下限
在泛型和通配符使用的时候,有时候会考虑到上下限的问题,
? extends T ,表示接受的类型是T,以及T的子类
? super T,表示接受的类型是T,以及T的父类
上下限的出现时为了类型检测更安全出现的。
public class Generic {
public static class info<T>{
private T i;
public T getI() {
return i;
}
public void setI(T i) {
this.i = i;
}
public String toString(){
return i.toString();
}
}
public static void main(String [] args){
info<Integer > info = new info<>();
info.setI(11);
say(info);
}
public static void say(info<? super Integer > arg){
System.out.println(arg);
}
//此处接受Integer,以及Integer的父类
/*
public static void say(info<? extends Integer > arg){
System.out.println(arg);
}*/
//此处接受Integer,以及Integer的子类
}