泛型

来源:互联网 发布:企业快报网络报送系统 编辑:程序博客网 时间:2024/04/29 12:58

泛型

           泛型应用

              泛型可以明确表示你要向集合中装哪种类型的数据,无法加入指定类型以外的数据.在从集合中取出数据时不用强制装转换.就可以赋值给相应对象.

//集合中使用泛型ArrayList<Integer> collection1 = new ArrayList<Integer>();collection1.add(1);collection1.add(2);//collection1.add("abc");    会报错int i = collection1.get(1);System.out.println(i);//构造方法的反射,使用泛型Constructor<String> constructor = String.class.getConstructor(StringBuffer.class);String str = constructor.newInstance(new StringBuffer("itheima"));System.out.println(str);
            

    泛型编译中的会去类型化处理:

    泛型是提供给javac编译器使用的,可以限定集合中的输入类型,让编译器挡住源程序中的非法输入,编译器编译带类型说明的集合时会去除掉“类型”信息,使程序运行效率不受影响,由于编译生成的字节码会去掉泛型的类型信息,只要能跳过编译器,就可以往某个泛型集合中加入其它类型的数据,例如,用反射得到集合,再调用其add方法即可。

ArrayList<Integer> collection1 = new ArrayList<Integer>();collection1.add(1);collection1.add(2);//泛型在编译器编译带类型说明的集合时会去除掉“类型”信息,集合编译后无法分辨集合内数据的类型信息ArrayList<String> collection2 = new ArrayList<String>();System.out.println(collection1.getClass() == collection2.getClass());//返回true//在Integer参数化的collection中加入StringMethod method = collection1.getClass().getMethod("add", Object.class);method.invoke(collection1, "abc");System.out.println(collection1.get(2));     //输出: abc


            泛型的术语于通配符

   泛型术语:

      整个称为ArrayList<E>泛型类型

      ArrayList<E>中的E称为类型变量或类型参数

     整个ArrayList<Integer>称为参数化的类型

      ArrayList<Integer>中的Integer称为类型参数的实例或实际类型参数

      ArrayList<Integer>中的<>念着typeof

      ArrayList称为原始类型

   参数化类型与原始类型的兼容性:

   参数化类型可以引用一个原始类型的对象
        Collection<String> c = new Vector();

  原始类型也可以引用一个参数化类型的对象,编译报告警告
       Collection c = new Vector<String>();

   参数化类型不考虑类型参数的继承关系:

   编译器不允许创建泛型变量的数组.

 

   通配符

<?>通配符

 ?可以引用其他各种参数化的类型,?通配符定义的变量主要用作引用,可以调用与参数化无关的方法,不能调用与参数化有关的方法。

   限定通配符的上边界<?Extends U>

    Vector<?extends Number> x = new Vector<Integer>();

   限定通配符的下边界<?Super I>

    Vector<?super Integer> x = new Vector<Number>();

  限定通配符总是包括自己。

  ?只能用作引用,不能用它去给其他变量赋值

  在方法的返回值出现?表示无法使用泛型

public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {//通配符?printCollection(new Collection<Integer>());//上边界通配符<? extends U>Vector<? extends Number> v = new Vector<Integer>();Vector<Integer> v3 = (Vector<Integer>) v;//下边界通配符 <? supper I>Vector<? super Integer> v2 = new Vector<Object>();Vector<Object> v4 = (Vector<Object>) v2;Vector<Number> v5 =  (Vector<Number>) getVector(new Vector<Integer>());Vector<? super Integer> v6 =  getVector(new Vector<Integer>());//Class<Integer> c = Class.forName("java.lang.Integer";)   报错 ?通配符不能赋值给参数化的类型}//使用?通配符可以引用其他各种参数化的类型,?通配符定义的变量主要用作引用,可以调用与参数化无关的方法,不能调用与参数化有关的方法。private static void printCollection(Collection<?> collection) {System.out.println(collection.size());for(Object obj : collection){System.out.println(obj);}}private static Vector<? super Integer> getVector(Vector<Integer> v){return v;}

     

     Map集合的泛型应用

Map<String, Integer> map = new HashMap<String, Integer>();map.put("aaa", 1);map.put("bbb", 2);map.put("ccc", 3);Set<Map.Entry<String, Integer>> entrySet = map.entrySet();for(Map.Entry<String, Integer> entry : entrySet){System.out.println(entry.getKey() + ":" + entry.getValue());}


   泛型方法

      只有引用类型才能作为泛型方法的实际参数,swap(new int[3],3,5);语句会报告编译错误。

      除了在应用泛型时可以使用extends限定符,在定义泛型时也可以使用extends限定符

      普通方法、构造方法和静态方法中都可以使用泛型。

     也可以用类型变量表示异常,称为参数化的异常,可以用于方法的throws列表中,但是不能用于catch子句中。

     在泛型中可以同时有多个类型参数,在定义它们的尖括号中用逗号分

//数组交换public static <T> void swap(T[] a, int i, int j){T tmp = a[i];a[i] = a[j];a[j] = tmp;}


      泛型方法习题

public class GenericTest2 {public static void main(String[] args) {Object o = "abc";String s = autoObject(o);Integer[] i = fill(new Integer[]{1}, 5);System.out.println(i[0]);Collection<Integer> collection = new ArrayList<Integer>();collection.add(9);printCollection(collection);copy1(new ArrayList<Integer>(), new Integer[10]);copy2(new Date[10], new Integer[10]);}//编写一个泛型方法,自动将Object类型的对象转换成其他类型。public static <T> T autoObject(Object obj){return (T)obj;}//定义一个方法,可以将任意类型的数组中的所有元素填充为相应类型的某个对象。public static <T> T[] fill(T[] a, T obj) {for(int i=0; i<a.length; i++) {a[i] = obj;}return a;}//采用自定泛型方法的方式打印出任意参数化类型的集合中的所有内容。/*在这种情况下,前面的通配符方案要比范型方法更有效,当一个类型变量用来表达两个参数之间或者参数和返回值之间的关系时,即同一个类型变量在方法签名的两处被使用,或者类型变量在方法体代码中也被使用而不是仅在签名的时候使用,才需要使用范型方法。*/public static <T> void printCollection(Collection<T> c){for(T obj: c){System.out.println(obj);}}//定义一个方法,把任意参数类型的集合中的数据安全地复制到相应类型的数组中。public static <T> void copy1(Collection<T> c, T[] a){int i = 0;for(T obj : c){a[i] = obj;i++;}}//定义一个方法,把任意参数类型的一个数组中的数据安全地复制到相应类型的另一个数组中。public static <T> void copy2(T[] dest, T[] a){for(int i=0; i<a.length; i++){dest[i] = a[i];}}}


  类型参数的类型推断:

   当某个类型变量只在整个参数列表中的所有参数和返回值中的一处被应用了,那么根据调用方法时该处的实际应用类型来确定,这很容易凭着感觉推断出来,即直接根据调用方法时传递的参数类型或返回值来决定泛型参数的类型

    当某个类型变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用方法时这多处的实际应用类型都对应同一种类型来确定,这很容易凭着感觉推断出来,例如:

    当某个类型变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用方法时这多处的实际应用类型对应到了不同的类型,且没有使用返回值,这时候取多个参数中的最大交集类型,例如,下面语句实际对应的类型就是Number了,编译没问题,只是运行时出问题:

    当某个类型变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用方法时这多处的实际应用类型对应到了不同的类型,并且使用返回值,这时候优先考虑返回值的类型,例如,下面语句实际对应的类型就是Integer了,编译将报告错误,将变量x的类型改为float,对比eclipse报告的错误提示,接着再将变量x类型改为Number,则没有了错误:

    参数类型的类型推断具有传递性,下面第一种情况推断实际参数类型为Object,编译没有问题,而第二种情况则根据参数化的Vector类实例将类型变量直接确定为String类型,编译将出现问题:


        泛型类

    如果类的实例对象中的多处都要用到同一个泛型参数,即这些地方引用的泛型类型要保持同一个实际类型时,这时候就要采用泛型类型的方式进行定义,也就是类级别的泛型.


  类级别的泛型是根据引用该类名时指定的类型信息来参数化类型变量的,例如,如下两种方式都可以:

 注意:

    在对泛型类型进行参数化时,类型参数的实例必须是引用类型,不能是基本类型。

    当一个变量被声明为泛型时,只能被实例变量、方法和内部类调用,而不能被静态变量和静态方法调用。因为静态成员是被所有参数化的类所共享的,所以静态成员不应该有类级别的类型参数。

public class GenericDao<T> {public static void main(String[] args) {   GenericDao<Integer> dao = null;   dao = new GenericDao<Integer>();   //dao.save("sdfdsf");   报错   dao.save(1);}    private T field1;    public void save(T obj){    field1 = obj;    }    public T getById(int id){return field1;}}

反射集合内泛型类型

public class GenericReflct {public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {GenericReflct gr = new GenericReflct();ArrayList al = new ArrayList<String>();gr.applyGeneric(al);System.out.println();Class cla = gr.getClass();Method method = cla.getMethod("applyGeneric", Collection.class);Type[] type = method.getGenericParameterTypes();ParameterizedType pType = (ParameterizedType)type[0];System.out.println(pType.getRawType());System.out.println(pType.getOwnerType());System.out.println(pType.getActualTypeArguments()[0]);}public <T> void applyGeneric(Collection<Data> c) throws NoSuchMethodException, SecurityException{Class cla = GenericReflct.class;Method method = cla.getMethod("applyGeneric", Collection.class);Type[] type = method.getGenericParameterTypes();ParameterizedType pType = (ParameterizedType)type[0];System.out.println(pType.getRawType());System.out.println(pType.getOwnerType());System.out.println(pType.getActualTypeArguments()[0]);}}




0 0
原创粉丝点击