泛型
泛型
Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递
常见形式有泛型类、泛型接口、泛型方法
语法:
<T,...> T称为类型占位符,表示一种引用类型
好处:
提高代码的重用性
防止类型转换异常,提高代码的安全性
泛型接口
eg :
public interface MyInterface<T> {
String name = "张三";//注意,不能使用泛型静态常量
T server(T t);
}
泛型类
eg :
public class MyGeneric<T> {//T是类型占用符,表示一种引用类型,如果编写多个使用逗号隔开
//使用泛型T
//1.创建变量
T t;
//2.添加方法
public void show(T t){
System.out.println (t);
}
//3.泛型作为方法的返回值
public T getT(){
return t;
}
}
泛型方法
eg :
public class MyGenericMethod {
//泛型方法
public <T> T show(T t){
System.out.println ("泛型方法:"+t);
return t;
}
}
泛型集合
概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致
特点:
编译时即可检查,而非运行时抛出异常
访问时,不必类型转换(拆箱)
不同泛型之间引用不能相互赋值,泛型不存在多态
eg :
public class TestGeneric {
public static void main(String[] args) {
//使用泛型创建对象
//注意:1.泛型只能使用引用类型,2.不同泛型类型对象之间不能互相赋值
MyGeneric<String> myGeneric = new MyGeneric<String> ( );
myGeneric.t = "hello";
myGeneric.show ("大家好,加油");
String steing = myGeneric.getT();
MyGeneric<Integer> myGeneric1 = new MyGeneric<Integer>();
myGeneric1.t = 100;
myGeneric1.show(200);
Integer integer = myGeneric1.getT();
//泛型接口
MyInterfaceImpl impl = new MyInterfaceImpl();
impl.server ("xxxxxxxxx");
MyInterfaceImpl2<Integer> impl2 = new MyInterfaceImpl2<>();
impl2.server(1000);
//泛型方法
MyGenericMethod myGenericMethod = new MyGenericMethod ();
myGenericMethod.show ("中国加油");
myGenericMethod.show (200);
myGenericMethod.show (3.14);
}
}

浙公网安备 33010602011771号