------- android培训、java培训、期待与您交流! ----------
泛型是提供给javac编译器使用的,可以限定集合中的输入类型,让编译器挡住源程序中的非法输入,编译器编译带类型说明的集合时会去除掉“类型”信息,使程序运行效率不受影响,对于参数化的泛型类型,getClass()方法的返回值和原始类型完全一样。由于编译生成的字节码会去掉泛型的类型信息,只要能跳过编译器,就可以往某个泛型集合中加入其它类型的数据,例如,用反射得到集合,再调用其add方法即可。
ArrayList<E>类定义和ArrayList<Integer>类引用中涉及如下术语:
整个ArrayList<E>称为泛型类型
ArrayList<E>中的E称为类型变量或类型参数
整个ArrayList<Integer>称为参数化的类型
ArrayList<Integer>中的Integer称为实际类型参数
ArrayList<Integer>中的<>念typeof
ArrayList称为原始类型
Vector<String> v = new Vector<Object>(); //错误!///不写<Object>没错,写了就是明知故犯 Vector<Object> v = new Vector<String>(); //也错误!参数化类型不考虑类型参数的继承关系:编译器不允许创建泛型变量的数组。即在创建数组实例时, 数组的元素不能使用参数化的类型,
例如,下面语句有错误:
Vector<Integer> vectorList[] = new Vector<Integer>[10];
下面的代码不会报错
Vector v1 = new Vector<String>();
Vector<Object> v = v1;
//对HashMap使用泛型 HashMap<String,Integer> maps = new HashMap<String, Integer>(); maps.put("zxx", 28); maps.put("lhm", 35); maps.put("flx", 33); //调用entrySet,后去set集合,该集合也使用泛型 Set<Map.Entry<String,Integer>> entrySet = maps.entrySet(); //对entrySet进行迭代并打印 for(Map.Entry<String, Integer> entry : entrySet){ System.out.println(entry.getKey() + ":" + entry.getValue()); }
static <E> void swap(E[] a, int i, int j) { E t = a[i]; a[i] = a[j]; a[j] = t; }只有引用类型才能作为泛型方法的实际参数,对于add方法,使用基本类型的数据进行测试没有问题,这是因为自动装箱和拆箱了。
swap(new int[3],3.5);语句会报告编译错误,这是因为编译器不会对new int[3]中的int自动拆箱和装箱了,因为new int[3]本身已经是对象了。
除了在应用泛型时可以使用extends限定符,在定义泛型时也可以使用extends限定符,
例如,Class.getAnnotation()方法的定义。
并且可以用&来指定多个边界,如<V extends Serializable & cloneable> void method(){}
普通方法、构造方法和静态方法中都可以使用泛型。
也可以用类型变量表示异常,称为参数化的异常,可以用于方法的throws列表中,但是不能用于catch子句中。
在泛型中可以同时有多个类型参数,在定义它们的尖括号中用逗号分,例如:
public static <K,V> V getValue(K key) { return map.get(key);}
public static <T> void copy1(Collection<T> src,T[] dest){ //把任意参数类型的集合中的数据安全地复制到相应类型的数组中。 } public static <T> void copy2(T[] src,T[] dest){ //把任意参数类型的数组中的数据安全地复制到相应类型的另一个数组中 }
Method applyMethod = GenericTest.class.getMethod("applyVector", Vector.class); //获取方法上的形参数组,反映参数化类型的实际类型 Type[] types = applyMethod.getGenericParameterTypes(); //强制转换为参数化类型 ParameterizedType pType = (ParameterizedType)types[0]; System.out.println(pType.getRawType());//class java.util.Vector //返回实际参数类型 System.out.println(pType.getActualTypeArguments()[0]);//class java.util.Date public static void applyVector(Vector<Date> v1){ }
------- android培训、java培训、期待与您交流! ----------