泛型---泛型类详解
泛型
JDK1.5引入,泛型的本质是参数化类型,把类型作为参数传递。
分类:
泛型类 泛型接口,泛型方法
格式
-
<T,....>T表示一种类型的占位符,T是一个引用类型,
-
可以是多种类型,但是要用逗号隔开,
好处
提高代码的重用性
防止类型转换异常,提高代码的安全性。
泛型类
语法:
-
类名<T,E,K>,
-
可以是一种类型也可以是多种类型。用逗号隔开类名<T,E,K>
泛型类
public class myGeneric<T> {
}
创建变量(不能实例化对象)
T t;
作为方法的参数
public void show(T t){
System.out.println(t);
}
作为方法的返回值
public T getT(){
return t;
}
为什么不能实例化对象
T t = new T();不可以这样子的
因为不能保证,运行时候,传递过来的引用类型的构造方法有没有,能不能访问,能不能用
//泛型类
public class myGeneric<T> {
//创建变量(不能实例化对象)
T t;
//作为方法的参数
public void show(T t){
System.out.println(t);
}
//作为方法的返回值
public T getT(){
return t;
}
}
//创建泛型类(写上引用类型)
myGeneric<String> myGeneric=new myGeneric<>();
public class genericText {
public static void main(String[] args) {
//创建泛型类对象
myGeneric<String> myGeneric=new myGeneric<String>();
//
myGeneric.t="给变量赋值";
System.out.println(myGeneric.t);
myGeneric.show("给show方法传参数");
String S=myGeneric.getT();
System.out.println("打印作为返回值: "+S);
//给变量赋值
//给show方法传参数
//打印作为返回值: 给变量赋值
myGeneric<Integer> inte=new myGeneric<>();
inte.t=333;
Integer i=inte.getT();
System.out.println(i);
inte.show(500);
//333
//500
注意
-
-
不同类型泛型对象不能相互复制

浙公网安备 33010602011771号