泛型是Java中的一个概念,您可以在其中启用类,接口和方法,以接受所有(引用)类型作为参数。换句话说,该概念使用户能够动态选择方法(类的构造函数)接受的引用类型。通过将类定义为泛型,可以使其成为类型安全的,即它可以作用于任何数据类型。
class Student<T>{ 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<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(); } }
输出结果
年龄值: 25.5 年龄值: 25 年龄值: 25
泛型类型用于引用类型,如果您将原始数据类型传递给它们,则无法生成原始数据类型,否则会生成编译时错误。
class Student<T>{ T age; Student(T age){ this.age = age; } } public class GenericsExample { public static void main(String args[]) { Student<Float> std1 = new Student<Float>(25.5f); Student<String> std2 = new Student<String>("25"); Student<int> std3 = new Student<int>(25); } }
GenericsExample.java:11: error: unexpected type Student<int> std3 = new Student<int>(25); ^ required: reference found: int GenericsExample.java:11: error: unexpected type Student<int> std3 = new Student<int>(25); ^ required: reference found: int 2 errors
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); 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 <T>sampleMethod(T[]) 1 error