泛型方法在 Java 中是什麼?
和泛型類類似,您還可以在 Java 中定義泛型方法。這些方法使用它們自己的型別引數。和區域性變數一樣,方法的型別引數範圍就在該方法中。
在定義泛型方法時,您需要在尖括號 (< T >) 內指定型別引數。這應放在方法的返回型別的前面。
您可以有多個型別引數,用逗號分隔。型別引數又稱為型別變數,是指定泛型型別名稱的識別符號。
型別引數可用於宣告返回型別,並且作為傳給泛型方法的引數的型別的佔位符,這些型別稱為實際型別引數。
示例 1
public class GenericMethod { <T>void sampleMethod(T[] array) { for(int i=0; i<array.length; i++) { System.out.println(array[i]); } } public static void main(String args[]) { GenericMethod obj = new GenericMethod(); Integer intArray[] = {45, 26, 89, 96}; obj.sampleMethod(intArray); String stringArray[] = {"Krishna", "Raju", "Seema", "Geeta"}; obj.sampleMethod(stringArray); } }
輸出
45 26 89 96 Krishna Raju Seema Geeta
示例 2
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; public class GenericMethodExample { public static <T> void arrayToCollection(T[] array, Collection<T> coll ) { for(int i=0; i<array.length; i++) { coll.add(array[i]); } System.out.println(coll); } public static void main(String args[]) { Integer [] intArray = {24, 56, 89, 75, 36}; ArrayList<Integer> al1 = new ArrayList<Integer>(); arrayToCollection(intArray, al1); String [] stringArray = {"Ramu", "Raju", "Rajesh", "Ravi", "Roshan"}; ArrayList<String> al2 = new ArrayList<String>(); arrayToCollection(stringArray, al2); } }
輸出
[24, 56, 89, 75, 36] [Ramu, Raju, Rajesh, Ravi, Roshan]
廣告