泛型
来源:互联网 发布:手机淘宝抢购页面刷新 编辑:程序博客网 时间:2024/05/22 04:27
泛型,何为泛型?
泛型:通过“参数化类型”来实现在同一份代码上操作多种数据类型。利用“参数化类型”将类型抽象化,从而实现灵活的复用。
泛型的分类,泛型分为泛型类,与泛型方法,泛型接口。
泛型类:
public static void main(String[] args) { int obj = 345; GenericityEntity genericityEntity=new GenericityEntity<Integer>(obj); System.out.println("int:" + genericityEntity.getObj()); String obj2 = "hello world"; GenericityEntity genericityEntity2=new GenericityEntity<String>(obj2); System.out.println("String:" + genericityEntity2.getObj()); }
public class GenericityEntity<T> { private T obj; public GenericityEntity(T obj) { this.obj=obj; } public T getObj() { return obj; } public void setObj(T obj) { this.obj = obj; }}泛型接口:
// 泛型接口的定义 interface DemoInterface<T1, T2> { T2 doSomeOperation(T1 t); T1 doReverseOperation(T2 t); } //实现泛型接口的类 class DemoClass implements DemoInterface<String, Integer> { public Integer doSomeOperation(String t) { //其他代码 } public String doReverseOperation(Integer t) { //其他代码 } }
泛型方法:
public class TestMethod { public static void main(String[] args) { test("a"); //T -->String } //定义泛型方法 public static <T> void test(T a){ System.out.println(a); } // extends表示上限<= ...表示可变参数,例如将其换成[]就成了数组 public static <T extends Closeable> void test(T... a){ for(T temp:a){ try { if(null!=temp){ temp.close();} } catch (IOException e) { e.printStackTrace(); } } }}
擦除泛型:
public class Student<T> { private T age; //private static T test; //泛型不能使用在静态属性上 public Student() { } public Student(T age) { this.age = age; } public T getAge() { return age; } public void setAge(T age) { this.age = age; }} /** * 泛型的擦除: 使用时 * 类似于 Object ,不等同于 Object */ public static void main(String[] args) { //擦除 -->没有指定 泛型的具体类型 Student student =new Student(); student.setAge(100); //100 -->int -->Integer -->Object Object obj=student.getAge(); System.out.println(obj); test(student);//编译不会类型检查,此处不会报错,因为Object类型相当于被擦除了 Student<Object> student2 =new Student<Object>(); //不等于 Object // test(student2); //会报错,因为这个地方已经申明了Object类型,就只能是Object类型 } public static void test(Student<Integer> stu){ ................... ................... }
注意:
public class ErasedTypeEquivalence { public static void main(String[] args) { //我们分别定义了一个接受String类型的List和一个接受Integer类型的List, //按照我们正常的理解,泛型ArrayList<T>虽然是相同的,但是我们给它传了不同的类型参数, //那么c1和2的类型应该是不同的。但是结果恰恰相反,运行程序发现二者的类型时相同的。这是为什么呢? //这里就要说到Java语言实现泛型所独有的——擦除 Class c1 = new ArrayList<String>().getClass(); Class c2 = new ArrayList<Integer>().getClass(); System.out.println(c1 == c2); } }
擦除例子:http://blog.csdn.net/quniMdejiangyou/article/details/77963440?locationNum=2&fps=1
阅读全文
0 0
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 使用Virtual Machine Manager 创建和管理虚拟机
- idea工具远程进行debug方式
- C语言双感叹号作用!!
- kotlin中学习笔记——null
- Java程序员们最常犯的10个错误
- 泛型
- session常用方法示例
- 2964: Boss单挑战
- 上云实践之使用VPN网关轻松构建混合云
- Apache的Order Allow,Deny 详解
- DRDS向ADS数据迁移指南
- [bzoj2276][POI2011]Temperature(单调队列)
- c# Aspose 图片处理(将Excel单元格中的图片拷贝到另一个Excel文件中)
- PB数据窗口保存前删除空行