一般的類和方法都是針對特定資料類型的,當寫一個對多種資料類型都適用的類和方法時就需要使用泛型程式設計,java的泛型程式設計類似於C++中的模板,即一種參數化型別的編程方法,具體地說就是將和資料類型相關的資訊抽象出來,主要提供通用的實現和邏輯,和資料類型相關的資訊由使用時參數決定。
1.泛型類/介面:
(1).泛型介面:
如一個提供產生指定類的介面:
public interface Gernerator<T>{T next() ;}public class A implement Generator<A>{A next(){return new A();}}
(2).泛型類:
一個使用泛型實現的棧資料結構如下:
public class LinkedListStack<T>{//節點內部類private static class Node<U>{U item;Node<U> next;Node(){item = null;next = null;}Node(U item, Node<U> next){this.item = item;this.next = next;}Boolean end(){return item == null && next == null;}}private Node<T> top = new Node<T>();public void push<T>(T item){top = new Node<T>(item, top);}public T pop(){T result = top.item;if(!top.end()){top = top.next();}return result;} }
使用這個使用泛型實現的棧,可以操作各種資料類型。
2.泛型方法:
例如:
public class GenericMethods{public <T> void f(T x){System.out.println(x.getClass().getName()) ;}public static void main(String[] args){GenericMethods gm = new GenericMethods();gm.f(“”);gm.f(1);gm.f(1.0);……} }
輸出結果為:
java.lang.String
java.lang.Integer
java.lang.Double
3.泛型集合:
Java中泛型集合使用的非常廣泛,在Java5以前,java中沒有引入泛型機制,使用java集合容器時經常遇到如下兩個問題:
a. java容器預設存放Object類型對象,如果一個容器中即存放有A類型對象,又存放有B類型對象,如果使用者將A對象和B物件類型弄混淆,則容易產生轉換錯誤,會發生類型轉換異常。
b. 如果使用者不知道集合容器中元素的資料類型,同樣也可能會產生類型轉換異常。
鑒於上述的問題,java5中引入了泛型機制,在定義集合容器物件時顯式指定其元素的資料類型,在使用集合容器時,編譯器會檢查資料類型是否和容器指定的資料類型相符合,如果不符合在無法編譯通過,從編譯器層面強制保證資料類型安全。
(1).java常用集合容器泛型使用方法:
如:
public class New{public static <K, V> Map<K, V> map(){return new HashMap<K, V>();}public static <T> List<T> list(){return new ArrayList<T>() ;}public static <T> LinkedList<T> lList(){return new LinkedList<T>();}public static <T> Set<T> set(){return new HashSet<T>();}public static <T> Queue<T> queue(){return new LinkedList<T>() ;};public static void main(String[] args){Map<String, List<String>> sls = New.map();List<String> ls = New.list();LinkedList<String> lls = New.lList();Set<String> ss = New.set();Queue<String> qs = New.queue();}}
(2).Java中的Set集合是數學上邏輯意義的集合,使用泛型可以很方便地對任何類型的Set集合進行數學運算,代碼如下:
public class Sets{//並集public static <T> Set<T> union(Set<T> a, Set<T> b){Set<T> result = new HashSet<T>(a);result.addAll(b);return result;}//交集public static <T> Set<T> intersection(Set<T> a, Set<T> b){Set<T> result = new HashSet<T>(a);result.retainAll(b);return result;}//差集public static <T> Set<T> difference(Set<T> a, Set<T> b){Set<T> result = new HashSet<T>(a);result.removeAll(b);return Result;}//補集public static <T> Set<T> complement(Set<T> a, Set<T> b){return difference(union(a, b), intersection(a, b));}}