Java泛型中的原始类型是什么?
泛型是Java中的一个概念,您可以在其中启用类,接口和方法,以接受所有(引用)类型作为参数。换句话说,该概念使用户能够动态选择方法(类的构造函数)接受的引用类型。通过将类定义为泛型,可以使其成为类型安全的,即它可以作用于任何数据类型。
要定义泛型类,您需要在类名称后的尖括号“<>”中指定要使用的类型参数,并将其视为实例变量的数据类型,然后继续执行代码。
示例-泛型类
class Person<T>{ T age; Person(T age){ this.age = age; } public void display() { System.out.println("Value of age: "+this.age); } }
用法 -在实例化泛型类时,您需要在尖括号内的类之后指定对象名称。因此,可以动态选择type参数的类型,并将所需的对象作为参数传递。
public class GenericClassExample { public static void main(String args[]) { Person<Float> std1 = new Person<Float>(25.5f); std1.display(); Person<String> std2 = new Person<String>("25"); std2.display(); Person<Integer> std3 = new Person<Integer>(25); std3.display(); } }
原始类型
在创建泛型类或接口的对象时,如果不提及类型参数,则将它们称为原始类型。
例如,如果在实例化Person类时观察上述示例,则需要在尖括号中为type参数(类型的类型)指定type。
如果您避免在尖括号中指定任何类型参数,并创建一个泛型类的对象,或者将它们简称为原始类型。
public class GenericClassExample { public static void main(String args[]) { Person per = new Person("1254"); std1.display(); } }
警告
这些将编译而不会出错,但会生成警告,如下所示。
Note: GenericClassExample.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details
以下是有关原始类型的一些值得注意的要点-
您可以将参数化的(泛型)类型分配给其原始类型。
public class GenericClassExample { public static void main(String args[]) { Person per = new Person(new Object()); per = new Person<String>("25"); per.display(); } }
输出结果
Value of age: 25
如果将原始类型分配给参数化类型,将生成警告。
public class GenericClassExample { public static void main(String args[]) { Person<String> obj = new Person<String>(""); obj = new Person(new Object()); obj.display(); } }
警告
Note: GenericClassExample.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
如果您的泛型类包含一个泛型方法,并且您尝试使用原始类型来调用它,那么将在编译时生成警告。
public class GenericClassExample { public static void main(String args[]) { Student std = new Student("Raju"); System.out.println(std.getValue()); } }
警告
Note: GenericClassExample.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.