泛型
將集合中的元素限定為一個特定的類型。
術語
- ArrayList<E> -- 泛型類型
- ArrayList -- 原始類型
- E -- 類型參數
- <> -- 讀作"typeof"
- ArrayList<Integer> -- 參數化的類型
- Integer -- 實際類型參數
幾點注意:
參數化類型和原始類型相互兼容
1
2
|
ArrayList collection1 = new ArrayList<Integer>(); //通過,無warning ArrayList<Integer> collection2 = new ArrayList(); //通過,有warning |
參數化類型不考慮類型參數的繼承關系
1
2
|
ArrayList<String> collection3 = new ArrayList<Object>(); //編譯不通過 ArrayList<Object> collection4 = new ArrayList<String>(); //編譯不通過 |
但是
1
2
|
ArrayList collection5 = new ArrayList<Integer>(); ArrayList<String> collection6 = collection5; //編譯通過 |
"?"通配符
"?"表示任意類型,使用"?"通配符可以引用各種參數化的類型,可以調用與參數化無關的方法(如size()方法),不能調用與參數化有關的方法(如add()方法)
通配符的擴展
限定通配符的上邊界
1
2
|
ArrayList<? extends Number > collection1= new ArrayList<Integer >(); //編譯通過 ArrayList<? extends Number > collection2= new ArrayList<String>(); //編譯不通過 |
限定通配符的下邊界
1
2
|
ArrayList<? super Integer > collection3= new ArrayList<Number >(); //編譯通過 ArrayList<? super Integer > collection4= new ArrayList<String>(); //編譯不通過 |
自定義泛型方法
C++模板函數
1
2
3
|
template < class T> T add(T x, T y){ return (T)(x+y); } |
而java的泛型基本上完全在編譯器中實現,用于編譯器執行類型檢查和類型判斷,然后生成普通的非泛型的字節碼,這種實現技術為“擦除”(erasure)。
"擦除"實例
泛型是提供給javac編譯器使用的,限定集合的輸入類型,編譯器編譯帶類型說明的集合時會去掉“類型”信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class GenericTest { public static void main(String[] args) { new GenericTest().testType(); } public void testType(){ ArrayList<Integer> collection1 = new ArrayList<Integer>(); ArrayList<String> collection2= new ArrayList<String>(); System.out.println(collection1.getClass()==collection2.getClass()); //兩者class類型一樣,即字節碼一致 System.out.println(collection2.getClass().getName()); //class均為java.util.ArrayList,并無實際類型參數信息 } } |
輸出
true
java.util.ArrayList
使用反射可跳過編譯器,往某個泛型集合加入其它類型數據。
只有引用類型才能作為泛型方法的實際參數 例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class GenericTest { public static void main(String[] args) { swap( new String[]{ "111" , "222" }, 0 , 1 ); //編譯通過 //swap(new int[]{1,2},0,1); //編譯不通過,因為int不是引用類型 swap( new Integer[]{ 1 , 2 }, 0 , 1 ); //編譯通過 } /*交換數組a 的第i個和第j個元素*/ public static <T> void swap(T[]a, int i, int j){ T temp = a[i]; a[i] = a[j]; a[j] = temp; } } |
但注意基本類型有時可以作為實參,因為有自動裝箱和拆箱。 例子(編譯通過了):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public class GenericTest { public static void main(String[] args) { new GenericTest().testType(); int a = biggerOne( 3 , 5 ); //int 和 double,取交為Number Number b = biggerOne( 3 , 5.5 ); //String和int 取交為Object Object c = biggerOne( "1" , 2 ); } //從x,y中返回y public static <T> T biggerOne(T x,T y){ return y; } } |
同時,該例還表明,當實參不一致時,T取交集,即第一個共同的父類。 另外,如果用Number b = biggerOne(3,5.5);改為String c = biggerOne(3,5.5);則編譯報錯:
Error:(17, 29) java: 不兼容的類型: 推斷類型不符合上限
推斷: java.lang.Number&java.lang.Comparable<? extends java.lang.Number&java.lang.Comparable<?>>
上限: java.lang.String,java.lang.Object
但是有一點沒搞清楚,我在IDEA里面單步調試,發現結果如下圖: 泛型調試截圖-1 不知道b為什么是Double類型的(但直接Double b接收返回值會編譯報錯)。不知道跟IDE有沒有關系,是不是IDE在debug時會顯示這個對象最精確的類型?
類型參數的類型推斷
編譯器判斷泛型方法的實際類型參數的過程稱為類型推斷。
當某個類型變量只在整個參數列表的所有參數和返回值中的一處被應用了,那么根據調用方法時該處的實際應用類型來確定。即直接根據調用方法時傳遞的參數類型或返回值來決定泛型參數的類型。 例如:
1
|
swap( new String[ 3 ], 1 , 2 ) -> static <E> void swap(E[]a, int i, int j) |
當某個類型變量在整個參數列表的所有參數和返回值中的多處被應用了,如果調用方法時這么多處的實際應用類型都 對應同一種類型,則泛型參數的類型就是該類型。 例如:
1
|
add( 3 , 5 ) -> static <T> T add(T a,T b) |
當某個類型變量在整個參數列表的所有參數和返回值中的*多處被應用了,如果調用方法時這么多處的實際應用類型 對應不同的類型,且沒有返回值,則取多個參數中的最大交集類型,即第一個公共父類。 例如:
1
|
fill( new Integer[ 3 ], 3.5 ) -> static <T> void fill(T a[],T v) |
該例子實際對應的類型就是Number,編譯通過,運行出問題。
當某個類型變量在整個參數列表的所有參數和返回值中的多處被應用了,如果調用方法時這么多處的實際應用類型對應不同的類型,且使用有返回值,則優先考慮返回值的類型
例如:
1
|
int x = add( 3 , 3.5 ) -> static <T> T add(T a,T b) |
上例編譯報錯,x類型改為float也報錯,改為Number成功。
參數類型的類型推斷具有傳遞性
例子:
copy(new Integer[5],new String[5]) -> static <T> void copy(T []a,T []b)
該例推斷實際參數類型為Object,編譯通過.
copy(new ArrayList<String>,new Integer[5]) -> static <T> void copy(Collection<T>a,T[]b)
該例則根據參數化的ArrayList類實例將類型變量直接確定為String類型,編譯報錯。
自定義泛型類
例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
public class GenericDao<T>{ public void add(T x){ } public T findById( int id){ return null ; } public void delete(T obj){ } public void delete( int id){ } public void update(T obj){ } public T findByUserName(String name){ return null ; } public <T> Set<T> findByConditions(String where){ return null ; } } |
注意:當一個變量被聲明為泛型時,只能被實例變量和方法調用(還有內嵌類型),而不能被靜態變量和靜態方法調用。因為靜態成員是被所參數化的類所共享的,所以靜態成員不應該有類級別的類型參數。
泛型方法和泛型類的比較
例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class A<T>(){ //泛型類的成員方法,該T受A后面的T的限制 public T memberFunc(){ return null ; } //泛型方法,這里的T和和類A的T是不同的 public static <T> T genericFunc(T a){ return null ; } public static void main(String[] args) { //編譯不通過 //Integer i = A<String>().findByUserName("s"); //編譯通過 Set<Integer> set= A<String>().findByConditions( "s" ); } } |
這里Integer i = A<String>().findByUserName("s");會編譯報錯:
Error:(35, 61) java: 不兼容的類型: java.lang.String無法轉換為java.lang.Integer
由這個例子可知,泛型方法的T和和類A的T是不同的。
泛型和反射
通過反射獲得泛型的實際類型參數
把泛型變量當成方法的參數,利用Method類的getGenericParameterTypes方法來獲取泛型的實際類型參數 例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
public class GenericTest { public static void main(String[] args) throws Exception { getParamType(); } /*利用反射獲取方法參數的實際參數類型*/ public static void getParamType() throws NoSuchMethodException{ Method method = GenericTest.class.getMethod("applyMap",Map.class); //獲取方法的泛型參數的類型 Type[] types = method.getGenericParameterTypes(); System.out.println(types[0]); //參數化的類型 ParameterizedType pType = (ParameterizedType)types[0]; //原始類型 System.out.println(pType.getRawType()); //實際類型參數 System.out.println(pType.getActualTypeArguments()[0]); System.out.println(pType.getActualTypeArguments()[1]); } /*供測試參數類型的方法*/ public static void applyMap(Map<Integer,String> map){ } } |
輸出結果:
1
2
3
4
|
java.util.Map<java.lang.Integer, java.lang.String> interface java.util.Map class java.lang.Integer class java.lang.String |