既然 Java 中已经有数组,为什么还需要引入泛型?

java 8object oriented programmingprogramming更新于 2025/11/14 20:28:17

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();
   }
}

输出

Value of age: 25.5
Value of age: 25
Value of age: 25

为什么我们需要泛型

在代码中使用泛型将获得以下优势 −

  • 编译时进行类型检查− 通常,当您使用类型(常规对象)时,如果传递了错误的对象作为参数,则会在运行时提示错误。

  • 而当您使用泛型时,错误会在编译时发生,这很容易解决。

  • 代码重用− 您可以使用泛型编写一次方法、类或接口,然后可以使用各种参数多次使用此代码。

  • 对于某些类型,对于正式类型,您需要强制类型转换并使用。使用泛型(在大多数情况下),您可以直接传递所需类型的对象,而无需依赖强制类型转换。


相关文章