黑马程序员_泛型总结(一个苹果是水果,一箱苹果不是水果)

来源:互联网 发布:python图像识别算法 编辑:程序博客网 时间:2024/04/20 07:26

---------------------- android培训、java培训、期待与您交流! ----------------------

jdk1.5之前的集合存在什么问题?
Arraylist<String>,Constructor<String>.
泛型是提供给javac compiler使用的,可以限定集合中的输入类型,让编译器挡住源程序中的非法输入,编译器编译带类型说明的集合时会去除掉“类型”信息,是程序运行效率不受影响,对于参数化的泛型类型,getClass()方法的返回值和raw type原始类型完全一样(定义一个arraylist<integer>,再定义一个arraylist<string>,然后分别用getclass,并用==比较,会法向true,因为他们俩指向同一份字节码,这份字节码不可能又是integer又是string的)。由于编译生成的字节码会去掉泛型的类型信息,只要能跳过编译器,就可以往某个泛型集合中加入其他类型的数据,例如,用反射得到集合,再调用其add方法即可。
泛型中的术语:
整个ArrayList<E>称为泛型类型;它中的<E>称为类型变量或类型参数;整个ArrayList<Integer>称为参数化的类型;Integer称为类型参数的实例或实际类型参数;<>念做typeof;ArrayList称为原始类型;
参数化类型不考虑类型参数的继承关系;如Vector<Integer> v=new Vector<Integer>;//也错误;
创建数组实例时,数组的元素不能使用参数化的类型,例如,Vector<Integer> vectorList[]=new Vector<Integer>[10];(l老师自己也原因不明)
泛型中的?通配符:使用?通配符可以引用其他各种参数化的类型,?通配符定义的变量主要是用作引用,可以调用与参数化无关的方法,不能调用与参数化有关的方法
限定通配符的上边界:Vector<? extends number> x=new Vector<Integer>();下边界:Vector<?number> x=new Vector<Integer>();限定通配符总是包括自己。
泛型的一个实例:在jsp中也经常要用到对map和set的操作
import java.util.*;
class g1
{
 public static void main(String[] args)
 {
  HashMap<String,Integer> maps=new HashMap<String,Integer>();
         maps.put("zxx",28); 
         maps.put("lhm",35); 
         maps.put("flx",33);
  
  Set<Map.Entry<String,Integer>> entrySet=maps.entrySet();
  for(Map.Entry<String,Integer> entry:entrySet)
  {
   System.out.println(entry.getKey()+":"+entry.getValue());
  }
 }
}
泛型只能处理引用类型的变量,不能代表基本类型,有时候可以自动装箱,有时候不能,所以用泛型处理基本类型时要留心;
定义泛型时可以使用extend限定符,并使用&指定多个边界,<V extends Serializable&cloneable> void method(){}
泛型练习题:
1.编写一个方法,自动将object类型能干的对象转换成其他类型;
private static <T> T autoConvert(Object obj)
{return (T)obj;}
2.将指定的obj充满任意类型的数组中
private static <T> void fillArray(T[] a,Object obj)
{
 for(int i=0;i<a.length;i++)
  a[i]=obj;
}
3.采用自定泛型的方法打印出任意参数化类型的集合中的所有内容。
前面的通配符会更有效;
4.定义一个方法,把任意参数类型的集合中的数据安全地复制到相应类型数组中;
在泛型中使用两个T,更安全;泛型中的类型推断具有传播性;

通过反射获得泛型的实际类型参数:
import java.util.*;
import java.lang.reflect.*;
class GenericTest
{
 public static void main(String[] args) throws Exception
 {
  Vector<Date> v1=new Vector<Date>();
  Method applyMethod =GenericTest.class.getMethod("applyVector",Vector.class);
  Type[] types=applyMethod.getGenericParameterTypes();
  ParameterizedType pType=(ParameterizedType)types[0];
  System.out.println(pType.getRawType());
  System.out.println(pType.getActualTypeArguments()[0]);
 }
 public static void applyVector(Vector<Date> v1)
 {}
}


---------------------- android培训、java培训、期待与您交流! ----------------------

原创粉丝点击