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

更新于:2019年9月9日

9K+ 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.