Java泛型方法中可以有多個型別引數嗎?
泛型是Java中的一個概念,您可以使用它使類、介面和方法能夠接受所有(引用)型別作為引數。換句話說,它是一個允許使用者動態選擇方法、類建構函式接受的引用型別的概念。透過將類定義為泛型,您可以使其型別安全,即它可以作用於任何資料型別。
要定義泛型類,您需要在類名後的尖括號“<>”中指定您使用的型別引數,您可以將其視為例項變數的資料型別,然後繼續編寫程式碼。
示例 - 泛型類
class Student<T>{
T age;
Student(T age){
this.age = age;
}
public void display() {
System.out.println("Value of age: "+this.age);
}
}用法 - 例項化泛型類時,您需要在類名後的尖括號中指定物件名稱。因此,動態選擇型別引數的型別並傳遞所需的物件作為引數。
public class GenericsExample {
public static void main(String args[]) {
Student<Float> std1 = new Student<Float>(25.5f);
std1.display();
Student<String> std2 = new Student<String>("25");
std2.display();
Student<Integer> std3 = new Student<Integer>(25);
std3.display();
}
}示例泛型方法
與泛型類類似,您也可以在Java中定義泛型方法。這些方法使用它們自己的型別引數。與區域性變數一樣,方法型別引數的作用域在方法內部。
定義泛型方法時,您需要在尖括號中指定型別引數,並將其用作區域性變數。
示例
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
多個引數
您也可以在Java的泛型中使用多個型別引數,只需要在尖括號中用逗號分隔指定另一個型別引數。
示例 - 方法中的多個引數
import java.util.Arrays;
public class GenericMethod {
public static <T, E> void sampleMethod(T[] array, E ele ) {
System.out.println(Arrays.toString(array));
System.out.println(ele);
}
public static void main(String args[]) {
Integer [] intArray = {24, 56, 89, 75, 36};
String str = "hello";
sampleMethod(intArray, str);
}
}輸出
[24, 56, 89, 75, 36] hello
示例 - 類中的多個引數
class Student<T, S> {
T t;
S s;
Student(T t, S s){
this.t = t;
this.s = s;
}
public void display() {
System.out.println("Value of "+this.t+" is: "+this.s);
}
}
public class GenericsExample {
public static void main(String args[]) {
Student<String, String> std1 = new Student<String, String>("Name", "Raju");
Student<String, Integer> std2 = new Student<String, Integer>("Age", 20);
Student<String, Float> std3 = new Student<String, Float>("Percentage", 96.5f);
std1.display();
std2.display();
std3.display();
}
}輸出
Value of Name is: Raju Value of Age is: 20 Value of Percentage is: 96.5
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP