在Java中声明泛型(类型)时的限制
泛型是Java中的一个概念,您可以在其中启用类,接口和方法,以接受所有(引用)类型作为参数。换句话说,该概念使用户能够动态选择方法(类的构造函数)接受的引用类型。通过将类定义为泛型,可以使其成为类型安全的,即它可以作用于任何数据类型。
对仿制药的限制
您不能以下面列出的某些方式和某些方案使用泛型-
您不能将原始数据类型与泛型一起使用。
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
您不能实例化泛型参数。
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(); T obj = new T(); } }
编译时错误
GenericsExample.java:15: error: cannot find symbol T obj = new T(); ^ symbol: class T location: class GenericsExample GenericsExample.java:15: error: cannot find symbol T obj = new T(); ^ symbol: class T location: class GenericsExample 2 errors
泛型类型参数不能为静态。
class Student<T>{ static 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(); } }
编译时错误
GenericsExample.java:3: error: non-static type variable T cannot be referenced from a static context static T age; ^ 1 error
您不能将一种数据类型的参数化类型转换为另一种。
import java.util.ArrayList; public class Generics { public static void main(String args[]) { ArrayList<Integer> list1 = new ArrayList<Integer>(); list1.add(25); list1.add(26); ArrayList<Number> list2 = list1; } }
编译时错误:
Generics.java:8: error: incompatible types: ArrayList<Integer> cannot be converted to ArrayList<Number> ArrayList<Number> list2 = list1; ^ 1 error
您不能创建泛型类型对象的数组。
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
泛型类型类不能扩展throwable类,因此,您不能捕获或抛出这些对象。
class Student<T>extends Throwable{ 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[]) { } }
编译时错误
GenericsExample.java:1: error: a generic class may not extend java.lang.Throwable class Student<T>extends Throwable{ ^ 1 error