一介紹:
在JavaSE1.5之前,沒有泛型的情況的下,通過對類型Object的引用來實現參數的“任意化”,“任意化”帶來的缺點是要做顯式的強制類型轉換,而這種轉換是要求開發者對實際參數類型可以預知的情況下進行的。對于強制類型轉換錯誤的情況,編譯器可能不提示錯誤,在運行的時候才出現異常,這是一個安全隱患。
泛型的好處是在編譯的時候檢查類型安全,并且所有的強制轉換都是自動和隱式的,提高代碼的重用率。
二、泛型參數:
java;">class Gen<T> { private T ob; //定義泛型成員變量 public Gen(T ob) { this.ob = ob; } public T getOb() { return ob; } public void setOb(T ob) { this.ob = ob; } public void showType() { System.out.println("T的實際類型是: " + ob.getClass().getName()); }}public class GenericParameter { public static void main(String[] args){ //定義泛型類Gen的一個Integer版本 Gen<Integer> intOb=new Gen<Integer>(100); intOb.showType(); int i= intOb.getOb(); System.out.println("value= " + i); System.out.println("----------------------------------"); //定義泛型類Gen的一個String版本 Gen<String> strOb=new Gen<String>("Hello Dylan!"); strOb.showType(); String s=strOb.getOb(); System.out.println("value= " + s); }}
output:
T的實際類型是: java.lang.Integer
value= 100
----------------------------------
T的實際類型是: java.lang.String
value= Hello Dylan!
三、泛型類:
class GenericsFoo<T> { private T x; public GenericsFoo(T x) { this.x = x; } public T getX() { return x; } public void setX(T x) { this.x = x; }}public class GenericClass { public static void main(String args[]){ GenericsFoo<String> strFoo=new GenericsFoo<String>("Hello Generics!"); GenericsFoo<double> douFoo=new GenericsFoo<double>(new double("33")); GenericsFoo<Object> objFoo=new GenericsFoo<Object>(new Object()); System.out.println("strFoo.getX="+strFoo.getX()); System.out.println("douFoo.getX="+douFoo.getX()); System.out.println("objFoo.getX="+objFoo.getX()); }}
output:
strFoo.getX=Hello Generics!
douFoo.getX=33.0
objFoo.getX=java.lang.Object@1d0fafc
四 限制泛型:
import java.util.ArrayList;import java.util.Collection;class CollectionGenFoo<T extends Collection> { private T x; public CollectionGenFoo(T x) { this.x = x; } public T getX() { return x; } public void setX(T x) { this.x = x; }}public class GenericRestrict { public static void main(String[] args) { CollectionGenFoo<ArrayList> listFoo = null; listFoo = new CollectionGenFoo<ArrayList>(new ArrayList()); CollectionGenFoo<? extends Collection> listFoo1 = null; listFoo1=new CollectionGenFoo<ArrayList>(new ArrayList()); System.out.println("實例化成功!"); }}
output:
實例化成功!
五 泛型方法:
public class GenericFunction { public <T> void f(T x) { System.out.println(x.getClass().getName()); } public static void main(String[] args) { GenericFunction ea = new GenericFunction(); ea.f(" "); ea.f(10); ea.f('a'); ea.f(ea); }}
output:
java.lang.String
java.lang.Integer
java.lang.Character
GenericFunction
-----------------------------
dylan presents.
總結
以上就是本文關于java中generic實例詳解的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
新聞熱點
疑難解答
圖片精選