Java泛型---学习(一)

来源:互联网 发布:wingide 4 linux 编辑:程序博客网 时间:2024/04/25 09:50

1.为什么会有泛型、需要泛型解决什么样的问题


2.泛型作用于编译阶段:

ArrayList<String> a = new ArrayList<String>();  a.add("CSDN_SEU_Cavin");  Class c = a.getClass();  try{      Method method = c.getMethod("add",Object.class);      method.invoke(a,100);      System.out.println(a);  }catch(Exception e){      e.printStackTrace();  }  

输出结果为

[CSDN_SEU_Cavin, 100]  

3.泛型的种类:泛型类 、泛型方法

public static class FX<T> {      private T ob; // 定义泛型成员变量        public FX(T ob) {          this.ob = ob;      }        public T getOb() {          return ob;      }        public void showTyep() {          System.out.println("T的实际类型是: " + ob.getClass().getName());      }  }      public static void main(String[] args) {          FX<Integer> intOb = new FX<Integer>(100);          intOb.showTyep();          System.out.println("value= " + intOb.getOb());          System.out.println("----------------------------------");            FX<String> strOb = new FX<String>("CSDN_SEU_Calvin");          strOb.showTyep();          System.out.println("value= " + strOb.getOb());  }  

与不使用泛型的类对比

public static class FX {      private Object ob; // 定义泛型成员变量        public FX(Object ob) {          this.ob = ob;      }        public Object getOb() {          return ob;      }        public void showTyep() {          System.out.println("T的实际类型是: " + ob.getClass().getName());      }  }        public static void main(String[] args) {          FX intOb = new FX(new Integer(100));          intOb.showTyep();          System.out.println("value= " + intOb.getOb());          System.out.println("----------------------------------");            FX strOb = new FX("CSDN_SEU_Calvin");          strOb.showTyep();          System.out.println("value= " + strOb.getOb());      }  
输出的结果都为:

T的实际类型是: java.lang.Integer  value= 100  ----------------------------------  T的实际类型是: java.lang.String  value= CSDN_SEU_Calvin  
需要自己去观察对比、明白其中的深意;很多时候我们都没有时间去神究原理、能够使用就好、虽然都明白理解了原理会更好、、、、、时间、、、、、、