转载:http://www.blogjava.net/fancydeepin
泛型的好处:
- /******* 不使用泛型类型 *******/
- List list1 = new ArrayList();
- list1.add(8080);//编译器不检查值
- String str1 = (String)list1.get(0); //需手动强制转换,如转换类型与原数据类型不一致将抛出ClassCastException异常
- /******* 使用泛型类型 *******/
- List<String> list2 = new ArrayList<String>();
- list2.add("value");//[类型安全的写入数据] 编译器检查该值,该值必须是String类型才能通过编译
- String str2 = list2.get(0); //[类型安全的读取数据] 不需要手动转换
- List<String> list1 = new ArrayList<String>();
- List<Integer> list2 = new ArrayList<Integer>();
- System.out.println(list1.getClass() == list2.getClass()); // 输出结果: true
- System.out.println(list1.getClass().getName()); // 输出结果: java.util.ArrayList
- System.out.println(list2.getClass().getName()); // 输出结果: java.util.ArrayList
- package test;
- import java.util.List;
- /**
- * -----------------------------------------
- * @描述 类型擦除
- * @作者 fancy
- * @邮箱 [email protected]
- * @日期 2012-8-25 <p>
- * -----------------------------------------
- */
- public class GenericsApp {
- public void method(List<String> list){
- }
- /*
- * 编译出错,这两个方法不属于重载,由于类型的擦除,使得这两个方法的参数列表的参数均为List类型,
- * 这就相当于同一个方法被声明了两次,编译自然无法通过了
- *
- public void method(List<Integer> list){
- }
- */
- }
- List<Object> list1;
- List<String> list2;
- list1 = list2; // 编译出错
- list2 = list1; // 编译出错
- List<?> list;
- List<Object> list1 = null;
- List<String> list2 = null;
- list = list1;
- list = list2;
- ArrayList<? extends Number> collection = null;
- collection = new ArrayList<Number>();
- collection = new ArrayList<Short>();
- collection = new ArrayList<Integer>();
- collection = new ArrayList<Long>();
- collection = new ArrayList<Float>();
- collection = new ArrayList<Double>();
- ArrayList<? super Integer> collection = null;
- collection = new ArrayList<Object>();
- collection = new ArrayList<Number>();
- collection = new ArrayList<Integer>();