java学习之泛型

    技术2025-12-16  9

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

     

    package cn.itcast.day1;

     

    import java.util.ArrayList;

     

    public class GenericTest {

     

    /**

    * @param args

    */

    public static void main(String[] args) throws Exception {

    // TODO Auto-generated method stub

         ArrayList<Integer> Collections1= new ArrayList<Integer>();

         ArrayList<String> Collections2= new ArrayList<String>();

         System.out.println(Collections1.getClass()==Collections2.getClass());

         Collections1.getClass().getMethod("add",Object.class).invoke(Collections1,"abc");

         System.out.println(Collections1.get(0));

    }

     

    }

     

     

    输出:

     true

    abc

     

    问题:

     

     Collections2.getClass().getMethod("add",Object.class).invoke(Collections2,11);

         System.out.println(Collections2.get(0));

    如果是String 放入 int类型的数据 就会报错:java.lang.Integer cannot be cast to java.lang.String

    好像是没跳过编译检查?

     

    泛型术语

     

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

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

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

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

    ArrayList<Integer>中的<>念type of

    ArrayList称为原始类型

     

    Collectoin<?>中,?是通配符,表示任意参数化类型的集合;

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

     

    泛型中?通配符的扩展

     

     

    //限定通配符的上边界:

             ArrayList<? extends Number> x1 = new ArrayList<Integer>();//正确 因为?号通配符表示任意类型但他继承了Number,表示只要是Number这个范围的就行!而Integer是Number的子类,所以可以

             //错误: ArrayList<? extends Number> x2 = new ArrayList<String>();因为String不属于Number的子类

             //限定通配符的下边界:

    ArrayList<? super Integer> x3 = new ArrayList<Number>();//可以?号必须是Integer的父类

    编译完的泛型集合已经去类型化了(就是可以忽略这个泛型集合里装的是什么类型,所以可以往这个泛型集合里加别的类型的对象)

     

     

    HashMap<String,Integer> maps=new HashMap<String,Integer>();

         maps.put("syh", 18);

         maps.put("syh1", 15);

         maps.put("syh2", 18);

         Set<Map.Entry<String,Integer>> entrySet= maps.entrySet();

         for(Map.Entry<String,Integer> entry:entrySet){//迭代;

         System.out.println(entry.getKey()+entry.getValue());

     

     

    输出:

     syh118

    syh15

    syh218

     

    注:如果 可前面参数key:String是相同的,则不管后面integer参数是否相同都只能存储一个,存储前应该会进行Key值检测看是否有相等(equals),如有就不放进去

     

    自定义泛型

     

       swap(new String[]{"abc","ass","sss"},1,2);

         swap(new int[]{1,3,4},1,2);//出错,只有引用类型才能作为泛型方法的实际参数

     

        public static <T> void swap(T[] a,int i,int j){

         T t= a[i];

         a[i]=a[j];

         a[j]=t;

        }

    只有引用类型才能作为泛型方法的实际参数

    最新回复(0)