泛型是Java中的一个概念,您可以在其中启用类,接口和方法,以接受所有(引用)类型作为参数。换句话说,该概念使用户能够动态选择方法(类的构造函数)接受的引用类型。通过将类定义为泛型,可以使其成为类型安全的,即它可以作用于任何数据类型。
示例class Student{
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 std1 = new Student(25.5f);
std1.display();
Student std2 = new Student("25");
std2.display();
Student std3 = new Student(25);
std3.display();
}
}
输出结果Value of age: 25.5
Value of age: 25
Value of age: 25
泛型类型数组
不,如果您尝试创建泛型类型对象的数组,则无法创建,会生成编译时错误。
示例class Student{
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[] std1 = new Student[5];
}
}
编译时错误GenericsExample.java:12: error: generic array creation
Student[] std1 = new Student[5];
^
1 error