【JAVASE基础】泛型Generic

1.泛型Generic
泛型技术是DK版本一大升级,源自于JDK1.5
泛型就是集合类<泛型>
1.1泛型的安全机制
软件升级:安全性提高,修复Bug错误改善用户体验增加功能,提升性能
JDK1.5里程碑版本
泛型作用 :强制了集合存储固定的数据类型
泛型的书写格式:
集合类<存储的数据类型>变量名 = new集合类<>b;
选择

在这里插入图片描述
●使用泛型的好处:
。安全性提高了
。程序的代码量减少
。避免了类型的强制转换
。程序的问题,由运行时期,提前到编译时期
1.2泛型中的E问题
E没有什么实际价值只是一个变量而已
在这里插入图片描述
1.3自定义泛型类

package com.sdjzu.generic;public class Generic1Test {public static void main(String[] args) {//创建自定义泛型类的对象Generic1<String> s1=new Generic1<String>();s1.setT("a");System.out.println("s1.getT() = " + s1.getT());Generic1<Double> s2=new Generic1<Double>();//泛型想要什么数据类型就要什么数据类型s2.setT(2.4);System.out.println("s2.getT() = " + s2.getT());}
}

在这里插入图片描述
1.4泛型方法

 //重写泛型方法public void method1(T t){System.out.println("t = " + t);}public T method2(){return t;}

1.5泛型接口
●实现类实现接口,不实现泛型

package com.sdjzu.generic;
/*
* 定义一个泛型接口,不指定类型
* */
public interface Generic<T> {public abstract void printer(T t);
}
package com.sdjzu.generic;public class GenericInter<T> implements Generic<T>{public void printer(T t){System.out.println(t);}
}
package com.sdjzu.generic;public class GenericInterTest {public static void main(String[] args) {GenericInter<String> s= new GenericInter<String>();s.printer("abs");}
}

在这里插入图片描述

●实现类实现接口,同时指定泛型

package com.sdjzu.generic.interface2;
/*
* 自定义泛型的接口
* */
public interface Generic<T> {public abstract void printer(T t);
}
package com.sdjzu.generic.interface2;
/*
* 自定义接口的实现类
* 指定泛型*/
public class GenericInter<String> implements Generic<String>{public void printer(String str){System.out.println("str = " + str);}
}
package com.sdjzu.generic.interface2;public class GenericInterTest {public static void main(String[] args) {GenericInter<String>  str= new GenericInter<>();str.printer("asjhdvfbajdhb");}
}

在这里插入图片描述


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部