在 Java 中定义泛型类/方法时,使用 T 作为类型参数是否强制性?
泛型是 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
<T> 是否强制性
为了指定泛型参数类型,我们在尖括号内使用 T。是的,必须指定它。如果您将其及其在泛型类和方法中的用法删除,它们将变成普通的类和方法。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP