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中定义泛型方法。这些方法使用它们自己的类型参数。与局部变量一样,方法的类型参数的范围也位于方法内。
在定义泛型方法时,您需要在尖括号中指定type参数并将其用作局部变量。
示例
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