您现在的位置: 万盛学电脑网 >> 程序编程 >> 网络编程 >> 编程语言综合 >> 正文

Java中泛型使用

作者:佚名    责任编辑:admin    更新时间:2022-06-22

   泛型: 1.5 之后出现 提高安全 1 泛型 确定 集合容器的类型。 2 <> 接收一种数据类型,(引用数据类型) ArrayList lis = new ArrayList() 目的: 将运行时期的 错误 转化到 编译时期,提高了安全性! 3 不需要 强制类型转换. 更加安全!

  泛型的 擦除: 泛型在编译时期使用!使用完毕直接擦除。 编译完的时候 不存在 泛型。

  好处: 使用了 泛型,不自需要强制类型转换?(多种数据类型) 为什么? 因为容器中只有一种数据类型。 取出数据之后,在处理数据细节!String 就是 很重要的。在现实的开发中。

  泛型自定义的类:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 //使用泛型 class Tools<t> {     private T obj;     public void setObject(T obj)     {         this.obj = obj;     }     public T getObject()     {         return this.obj;     }   }</t>

  泛型应用在方法上:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 class Test<e> {     //泛型用在方法上     //当类中的某个方法所使用的类型只有在类上的类型确定了才能确定时,就在方法上使用          //泛型     //否则不用泛型     public void func(E e)     {         System.out.println(e);     }       //该方法单独使用泛型:    方法使用的类型不确定,而且什么类型都行     //这个    方法被调用时,类型才确定     public <t> void show(T e)     {         System.out.println(e);     }               //静态是随着类的加载而加载,这是不存在类型,所以静态方法只能自己定义泛型     public static <w> void function(W e)//Test.function()      {         System.out.println(e);     }         public void ff(int a,int b)     {        System.out.println(a+b);     } }</w></t></e>

  泛型 定义在接口上:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 //泛型用在接口上   interface inter<t> {     public void show(T t); } class Test implements inter<string> {     public void show(String t)     {               } } class Demo<e>  implements inter<e> {     public void show(E t)     {         System.out.println(t);     } } class  Demo9 {     public static void main(String[] args)     {         Demo<string> d = new Demo<string>();         d.show(99);// error     } } </string></string></e></e></string></t>