在 Java 中实例化参数化类型 (泛型) 时传递基本值?
泛型是 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 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
广告