JDK1.5版本之後出現的新特性,用於解決安全問題,時一種安全機制。java
好處:程序員
1.將運行時出現的問題ClassCastException,轉移到了編譯時期,方便於程序員解決問題,讓運行問題減小,安全。安全
2.避免了強制轉換的麻煩。框架
泛型格式:經過<>來定義要操做的引用數據類型。ide
在使用java提供的對象時,何時寫泛型呢?spa
一般在集合框架中很常見,只要見到<>就要定義泛型。code
其實<>就是用來接收類型的。對象
當使用集合時,將集合中要存儲的數據類型做爲參數傳遞到<>中便可。blog
public class GenericDemo { public static void main(String[] args) { TreeSet<String> ts = new TreeSet<String>(new MyComparetor()); ts.add("s"); ts.add("fff"); ts.add("hdh"); ts.add("oamsc"); Iterator<String> it = ts.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } class MyComparetor implements Comparator<String> { @Override public int compare(String o1, String o2) { int num = new Integer(o1.length()).compareTo(new Integer(o2.length())); if (num == 0) { return o1.compareTo(o2); } return num; } }
泛型類:it
當類中操做的引用數據類型不肯定的時候,早期定義Object來完成擴展。
如今定義泛型來完成擴展。
泛型方法:
泛型類定義的泛型,在整個類中有效,若是被方法使用,那麼泛型類的對象明確要操做的具體類型後,全部方法要操做的類型就已經固定了。
爲了讓不一樣方法操做不一樣類型,並且類型還不肯定,那麼能夠將泛型定義在方法上。
靜態方法不能夠訪問 類上定義的泛型。
若是靜態方法操做的引用數據類型不肯定,能夠將泛型定義在方法上。
T:表明具體類型
?:不明確類型,佔位符。
public class GenericDemo { public static void main(String[] args) { ArrayList<String> ts = new ArrayList<String>(); ts.add("s"); ts.add("fff"); ts.add("hdh"); ts.add("oamsc"); ArrayList<Integer> ts1 = new ArrayList<Integer>(); ts1.add(1); ts1.add(2); ts1.add(3); ts1.add(4); printList(ts); printList_1(ts); printList(ts1); printList_1(ts1); } public static void printList(ArrayList<?> al) { Iterator<?> it = al.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } public static <T> void printList_1(ArrayList<T> al) { Iterator<T> it = al.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
類型限定:
?:通配符,能夠理解爲佔位符。
<? extends E>:能夠接收E類型或者E子類類型,上限。
<? super E>:能夠接收E類型或者E父類類型,下限。