Java之泛型编程

来源:互联网 发布:足球教练考试软件 编辑:程序博客网 时间:2024/05/16 11:40

1.概念

  泛型就是参数化类型。泛型的好处是在编译的时候检查类型安全,并且所有的强制转换都是自动和隐式的,提高代码的重用率。

2.案例

1)先看下面案例

//不适用泛型编程Apple app0=new Apple();Apple app1=new Apple();List li = new ArrayList();li.add(app0);//添加非需要类型时发现不了错误。li.add(app1);Apple appUsed=(Apple)li.get(0);//使用泛型编程如下Apple app0=new Apple();Apple app1=new Apple();List<Apple> li = newArrayList<Apple>();li.add(app0);//如果添加的对象类型错误,编译器即可发现。指定容器要持有的对象类型,用编译器来保证类型的正确性。li.add(app1);Apple appUsed=li.get(0);

使用泛型的优点:大型应用时能显著降低程序的复杂度;泛型为较大的优化带来可能: 可以在编译期发现该类错误,而且在取出元素时不需要再进行类型判断,从而提高了程序的运行时效率。 

2)泛型类

有两个类如下,要构造两个类的对象,并打印出各自的成员x。

public classStringFoo {    private Stringx;    public StringFoo(String x) {        this.x = x;    }    public String getX() {        return this.x;    }    public void setX(String x) {        this.x = x;    }} public classDoubleFoo {    private Doublex;    public DoubleFoo(Double x) {        this.x = x;    }    public Double getX() {        return this.x;    }    public void setX(Double x) {        this.x = x;    }}

用泛型来实现:

public classGenericsFoo<T> {    private Tx;    public GenericsFoo(T x) {        this.x = x;    }    public T getX() {        return this.x;    }    public void setX(T x) {        this.x = x;    }} public classGenericsFooDemo {    public static void main() {        GenericsFoo<String>strFoo = newGenericsFoo<String>("Helloworld!");        GenericsFoo<Double>doubleFoo = newGenericsFoo<Double>(5.20);        System.out.println("strFoo.getX="+strFoo.getX());        System.out.println("doubleFoo.getX="+doubleFoo.getX());    }}

 3)泛型方法

是否拥有泛型方法,与其所在的类是否泛型没有关系。要定义泛型方法,只需将泛型参数列表置于返回值前。

public classGenericsFooDemo {     public <T>void f(T x) {        System.out.println(x.getClass().getName());    }       public static void main() {        GenericsFooDemoea = newGenericsFooDemo();        ea.f("ea");        ea.f(10);    }}

使用泛型方法时,不必指明参数类型,编译器会自己找出具体的类型。泛型方法除了定义不同,调用就像普通方法一样。需要注意,一个static方法,无法访问泛型类的类型参数,所以,若要static方法使用泛型能力,必须使其成为泛型方法。

 

4)限制泛型和通配符

class GenericsFoo<T extends Collection>,这样类中的泛型T只能是Collection接口的实现类,传入非Collection接口编译会出错。

class GenericsFoo<? extends Collection>,“?”代表未知类型(通配符),这个类型实现Collection接口。<? extends 类型>表示?类型是某个类型的子类型。


转自:http://www.cnblogs.com/devinzhang/archive/2012/02/08/2342364.html

0 0