泛型初步,泛型类

来源:互联网 发布:海关数据怎么查 编辑:程序博客网 时间:2024/05/29 11:12

泛型:JDK1.5版本以后出现的新特性。用于解决安全问题,是一个类型安全机制。

好处:

1,在运行时期出现问题ClassCastException ,转移到了编译时期。

方便程序员解决问题,让运行时期问题减少,安全。

2,避免了强制转换的麻烦。

3,泛型格式:通过<>来定义要操作的引用数据类型。

在使用java提供的对象时,什么时候写泛型呢?

通常在集合框架中很常见,只要见到<>就要定义泛型。

其实<>就是用来接收类型的

当使用集合时,将集合中要存储的数据类型作为参数传递到<>中即可。

定义泛型时,放到返回值类型的前面。


运行结果为:

djehnwif:83eefde:6de3:345t645gf:8


4,泛型类:

class worker{}class poet{}class utils<QQ>{private QQ q;public void setObject(QQ q){this.q=q;}public QQ getObject(){return q;}}public class GenericDemo2 {public static void main(String[] args){utils<worker> u=new utils<worker>();u.setObject(new worker());worker w=u.getObject();}}


<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">5,当泛型定义在方法上:</span>

class Demo{public<T> void show(T t){System.out.println("show:"+t);}public<Q> void print(Q q){System.out.println("print:"+q);}}public class GenericDemo3 {public static void main(String[] args){Demo d=new Demo();d.show("haha");d.show(new Integer(4));d.print(6);d.print("deiuj");}}
运行结果:

show:hahashow:4print:6print:deiuj


6,注意:

静态方法不可访问类上定义的泛型。例如下面代码就会编译失败

class Demo<T>{public static void show(T t){System.out.println("show:"+t);}
}
如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上,例如:
class Demo<T>{public static<span style="color:#ff0000;"><W></span> void show(W w){System.out.println("show:"+w);}
}
7 泛型定义在接口上,代码如下:

interface inter<T>{void show(T t);}class InterImp implements inter<String>{public void show(String str){System.out.println("show:"+str);}}public class GenericDemo4 {public static void main(String[] args){InterImp i=new InterImp();i.show("hahah");}}
打印结果:

show:hahah





0 0
原创粉丝点击