文章參考自:http://www.cnblogs.com/iyangyuan/archive/2013/04/09/3011274.html
有泛型方法還有泛型類。
類似於如下代碼定義的泛型是泛型方法 :
package com.test.GenericTest;
import java.util.ArrayList;
import java.util.List;
package com.test.GenericTest;import java.util.ArrayList;import java.util.List;public class GenericFoo<T>{private T value ;public T getValue(){return value;}public void setValue(T value){this.value = value;}public static void main(String[] args){GenericFoo<String> foo1 = new GenericFoo<String>();List<String> list = new ArrayList<String>();foo1.setValue("helloworld");System.out.println(foo1.getValue());}}
上述代碼定義了一個GenericFoo<String>類 。
類似下面定義的方式的叫泛型方法
public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass());System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }
傳回型別T[] 前面必須加上<T> 聲明 為 泛型方法。
泛型類,是在執行個體化類的時候指明泛型的具體類型;泛型方法,是在調用方法的時候指明泛型的具體類型。 注意留心:泛型方法調用的時候指明了泛型T是什麼類型的。
而泛型類是在類的初始化的時候指明泛型T的類型的 例如 ArrayList<String> list = new ArrayList(); 這樣是聲明了一個泛型類。