Java 中的泛型方法可以有多个类型参数吗?

java 8object oriented programmingprogramming更新于 2024/10/13 12:13:00

泛型是 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

相关文章