泛型
前言
- 本质是参数化类型,把类型作为参数传递
- 常见形式有泛型类、泛型接口、泛型方法
- 语法 T成为类型占位符,表示一种引用类型,可以写多个逗号隔开
- 好处
- 提高代码重用性
- 防止类型转换异常,
- 提高代码安全性
提示:以下是本篇文章正文内容,下面案例可供参考
一、泛型类
语法:public class A{ …}
public class FX <T>{
T t;//创建变量
public void show(T t1){//作为方法参数
System.out.println(t1);
}
public T get(){//作为方法返回值
return t;
}
}
public class test5 {
public static void main(String []arg){
FX<String> a = new FX<>();
a.t = "hello FX";
a.show("hello FX1");
String b = a.get();
System.out.println(b);
}
}
/*
hello FX1
hello FX
*/
二、泛型接口
语法:interfaces A{…};
不可定义泛型静态常量
public interface test<T> {
void A();
T B();
}
可继续实现为泛型类
public class test3<T> implements test<T>{
T t;
public void A() {
System.out.println(t);
}
public T B() {
return t;
}
}
public class test1 implements test<String>{
public void A() {
System.out.println("大帅哥");
}
public String B() {
return "小帅哥";
}
}
public static void main(String []args){
test1 a =new test1();
String b=a.B();
a.A();
System.out.println(b);
}
}
//大帅哥
//小帅哥
三、泛型方法
语法:public T show(T t){ }
public class MyGenericMethod{
//泛型方法
public <T> T show(T t){
sout("泛型方法" + t);
return t;
}
}
//调用
MyGenericMethod myGenericMethod = new MyGenericMethod();
myGenericMethod.show("字符串");// 自动类型为字符串
myGenericMethod.show(200);// integer类型
myGenericMethod.show(3.14);// double类型