轉載: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>();