泛型是Java中的一个概念,您可以在其中启用类,接口和方法,以接受所有(引用)类型作为参数。换句话说,该概念使用户能够动态选择方法(类的构造函数)接受的引用类型。通过将类定义为泛型,可以使其成为类型安全的,即它可以作用于任何数据类型。
示例class Student{
T age;
Student(T age){
this.age = age;
}
public void display() {
System.out.println("年龄值: "+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();
}
}
输出结果年龄值: 25.5
年龄值: 25
年龄值: 25
传递原始值
泛型类型用于引用类型,如果您将原始数据类型传递给它们,则无法生成原始数据类型,否则会生成编译时错误。
示例class Student{
T age;
Student(T age){
this.age = age;
}
}
public class GenericsExample {
public static void main(String args[]) {
Student std1 = new Student(25.5f);
Student std2 = new Student("25");
Student std3 = new Student(25);
}
}
编译时间错误GenericsExample.java:11: error: unexpected type
Student std3 = new Student(25);
^
required: reference
found: int
GenericsExample.java:11: error: unexpected type
Student std3 = new Student(25);
^
required: reference
found: int
2 errors
示例public class GenericMethod {
void sampleMethod(T[] array) {
for(int i=0; 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);
char charArray[] = {'a', 's', 'w', 't'};
obj.sampleMethod(charArray);
}
}
输出结果GenericMethod.java:16: error: method sampleMethod in class GenericMethod cannot be applied to given types;
obj.sampleMethod(charArray);
^
required: T[]
found: char[]
reason: inference variable T has incompatible bounds
equality constraints: char
upper bounds: Object
where T is a type-variable:
T extends Object declared in method sampleMethod(T[])
1 error