你能在 Java 中创建泛型类型的数组吗?
java 8object oriented programmingprogramming更新于 2024/10/13 12:54: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(); } }
输出
Value of age: 25.5 Value of age: 25 Value of age: 25
泛型类型数组
不可以,我们无法创建泛型类型对象数组,如果您尝试这样做,将会产生编译时错误。
示例
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>[5]; } }
编译时错误
GenericsExample.java:12: error: generic array creation Student<Float>[] std1 = new Student<Float>[5]; ^ 1 error