---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------
JDK1.5新特性:泛型
jdk1.5的集合类希望你在定义集合时,明确表示你要向集合中装哪种类型的数据,无法加入指定类型以外的数据。
例:ArrayList<Integer> collection2 = new ArrayList<Integer>();
泛型是提供给javac编译器使用的,可以限定集合中输入的类型,让编译器挡住源程序中的非法输入,编译器编译带类型说明的集合时会除掉“类型”信息,是程序运行效率不受影响,对于参数化的泛型类型,getClass()方法的返回值和原始类型完全一样。由于编译生成的字节码会去掉泛型的类型信息,只要能跳过编译器,就可以往某个泛型集合中加入其它类型的数据,例如,用反射得到集合,再调用其add方法即可。
泛型的简单了解:
ArrayList<E>类定义和ArrayList<Integer>类引用中涉及如下术语:
1,整个称ArrayList<E>为泛型类型
2,ArrayList<E>中的E称为类型变量或类型参数
3,整个ArrayList<Integer>称为参数化的类型
4,ArrayList<Integer>中的Integer称为类型参数的实例或实际类型参数
5,Arraylist<Integer>中的<>念着typeof
6,ArrayList称为原始类型
参数化类型与原始类型的兼容性:
参数化类型可以引用一个原始类型的对象,编译报告警告,例如:
Collection<String> c = new Vector();
原始类型可以引用一个参数化类型的对象,编译报告警告,例如:
Collection c = new Vector<String>();
参数化类型不考虑类型参数的继承关系:
Vector<String> v = new Vector<Object>();//错误
Vector<Object> v = new Vector<String>();//也错误!
在创建数组实例时,数据的元素不能使用参数化的类型,例如,下列语句有错误:
Vector<Integer> vector ist[] = new Vector<Integer>[10];
思考一下:下面代码会报错误吗?
Vector v1 = new Vector<String>(); //没错
Vector<Object> v = v1; //没错
泛型中的?通配符
public static void printCollection(Collection<?> cols) //表示可以接收任何类型参数的集合
{
}
如果用了?号,里头就不能确定是什么类型,就不能出现cols.add("String");
泛型中的?通配符的扩展
限定通配符的上边界:
正确:Vector<? extends Number> x = new Vector<Integer>();
错误:Vector<? extends Number> x = new Vector<String>();
限定通配符的下边界:
正确:Vector<? super Integer> x = new Vector<Number>();
错误:Vector<? super Integer> x = new Vector<Byte>();
提示:限定通配符总是包括自己;
泛型集合类的综合案例:
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());
泛型在异常处理:
private static <T extends Exception> sayHello() throw T
{
try{
}catch(Exception e){
throw(T)e;
}
}
通配符方案比泛型方法更有效:
public static <T> void printCollection2(Collection<T> collection){
System.out.println(collection.size());
for(Object obj:collection)
System.out.println(obj);
}
collection.add(obj2);
T的时候可以用add方法。
程序员名称:crud(增删改查)
高难度知识点:
public static void applyVector(Vector<Date> v1){
}
想要知道Vector里的类型参数,必须用反射:
Method applyMethod = GenericTest.class.getMethod("applyVector",Vector.class);
Type[] types = applyMethod.getGenericParameterTypes();
ParameterizedType pType = (ParameterizedType) types[0];
System.out.println(pType.getRawType());
Systemout.println(pType.getActualTypeArguments()[0]);
---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------详细请查看:http://edu.csdn.net