为什么要使用泛型?
可以使集合内只添加指定类型,从而保证了类型安全。
Java中泛型只在编译阶段有效,即泛型信息不回机内到运行时阶段。
class A<T>{
private T key;
public void setKey(T key){
this.key=key;
}
public T getKey(){
return key;
}
}
A<String> temp = new A<String>();
Temp.setKey(“12asd”);
定义泛型接口
interface A<T>{
T test(T t);
}
实现泛型接口
class B1<T> implements A<T>{
public T test(T t){
return t;
}
}
class B2 implements A<String>{
public Strring test(String t){
return null;
}
}
在引用未传入泛型实参的类时,可添加不同泛型数据类型
B1<Object> b1 = new B1<Object>();
B1<String> b1 = new B1<String>();
B1<Integer> b1 = new B1<Integer>();
在引用传入泛型实参的类时,其泛型被规定。
B2 b2 = new B2();
泛型方法,在调用之前没有固定的数据类型,会在调用时,确定泛型的具体数据类型
class C{
//无返回值的泛型方法
public <T> void test(T s){
T t = s;
}
//有返回值的泛型方法
public <T> T test1(T s){
return s;
}
//可变参数的泛型方法
public <T> test2(T… strs){
for(T s : strs){
System.out.println(s);
}
}
}
本文地址:https://blog.csdn.net/qq_37915248/article/details/107898960
如对本文有疑问, 点击进行留言回复!!
关于在IDEA中SpringBoot项目中activiti工作流的使用详解
视频编辑工具ACDSee Luxea Video Editor安装及激活图文教程
java spring整合junit操作(有详细的分析过程)
网友评论