加强学习2

来源:互联网 发布:视频监控软件下载 编辑:程序博客网 时间:2024/05/16 05:01

36-37课:泛型

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

 

使用泛型集合,可以将一个集合中的元素限定为一个特定类型,集合中只能存取同一个类型的对象,这样更安全,编译器也可以知道这个对象的概念,不需要对对象进行强制类型转化,这样更方便。

 

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

1】 参数化类型可以引用一个原始数据的类型

Collection<String> c=new Vector();

2】 原始数据可以引用一个参数化数据类型的对象;

Collection c=new Vector<String>

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

Vector <String> v=new Vertor<Object> //错误

Vector <Object> v=new Vertor<String> //错误

3】 在创建数组实例时,数组的元素不能使用参数化的类型。

Vector<Integer> vectorlist[]=new Vector<Integer>[10]; //错误

 

import

java.util.ArrayList; 

GenericTest { 

/**    

*@throwsNoSuchMethodException

*@throwsInvocationTargetException

*@throwsIllegalAccessException

*@throwsSecurityException

*@throwsIllegalArgumentException

*/   main(String[] args)IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { 

       ArrayList<String> collection2= ArrayList<String>();       collection2.add();                         ArrayList<Integer> collection3= ArrayList<Integer>();       collection3.add(23); 

"add"class"sdfesdf"

out

out

}publicstaticvoid

out

for

out

 

 

 

39、泛型集合的综合应用案例

 

       HashMap<String,Integer> maps = HashMap();       maps.put(, 32);       maps.put(, 29);       maps.put(, 41);             Set<Map.Entry<String,Integer>> entrySet=maps.entrySet();             (Map.Entry<String,Integer> entry:entrySet){                      System..println(entry.getKey()++entry.getValue());          }          }

 

[] str6= String[]{,,,};       swap(str6,1,2);       (String str:str6){          System..println(str);      }

       GenericDao<Point> dao= GenericDao<Point> ();             dao.add( Point(4,6));            Point s= dao.findById(1);      

当一个变量被声明为泛型时,只能被实例变量和方法调用(还有内嵌变量),而不能被静态变量和静态方法调用。静态方法不应该有类级别的类型参数。

 

原创粉丝点击