当前位置:编程学习 > JAVA >>

Java之泛型编程

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 = new ArrayList<Apple>();  
li.add(app0);        //如果添加的对象类型错误,编译器即可发现。指定容器要持有的对象类型,用编译器来保证类型的正确性。  
li.add(app1);  
   
Apple appUsed=li.get(0);  
 
 
  使用泛型的优点:大型应用时能显著降低程序的复杂度;泛型为较大的优化带来可能: 可以在编译期发现该类错误,而且在取出元素时不需要再进行类型判断,从而提高了程序的运行时效率。 
2)泛型类
有两个类如下,要构造两个类的对象,并打印出各自的成员x。
public class StringFoo {  
  
    private String x;  
  
    public StringFoo(String x) {  
             this.x = x;  
    }  
  
  
    public String getX() {  
             return x;  
    }  
  
     public void setX(String x) {  
             this.x = x;  
    }  
 }  
  
 public class DoubleFoo {  
  
    private Double x;  
  
    public DoubleFoo(Double x) {  
             this.x = x;  
    }  
  
    public Double getX() {  
             return x;  
    }  
  
     public void setX(Double x) {  
             this.x = x;  
    }  
 }  
 
 
用泛型来实现
public class GenericsFoo<T> {  
  
  private T x;  
  
  public GenericsFoo(T x) {  
     this.x = x;  
  }  
  
   public T getX() {  
     return x;  
  }  
  
  public void setX(T x) {  
     this.x = x;  
  }  
}  
  
   
代码实现:  
  
 public class GenericsFooDemo {  
  
  public static void main(String args[]){  
  
     GenericsFoo<String> strFoo=new GenericsFoo<String>("Hello Generics!");  
     GenericsFoo<Double> douFoo=new GenericsFoo<Double>(new Double("33"));  
     GenericsFoo<Object> objFoo=new GenericsFoo<Object>(new Object());  
  
     System.out.println("strFoo.getX="+strFoo.getX());  
     System.out.println("douFoo.getX="+douFoo.getX());  
     System.out.println("objFoo.getX="+objFoo.getX());  
  }  
}  
 
3)泛型方法
是否拥有泛型方法,与其所在的类是否泛型没有关系。要定义泛型方法,只需将泛型参数列表置于返回值前。
public class ExampleA {  
  
  public <T> void f(T x) {  
     System.out.println(x.getClass().getName());  
  }  
  
  public static void main(String[] args) {  
  
     ExampleA ea = new ExampleA();  
  
     ea.f("ea ");  
     ea.f(10);  
     ea.f('a');  
  }  
}  
 
 
  使用泛型方法时,不必指明参数类型,编译器会自己找出具体的类型。泛型方法除了定义不同,调用就像普通方法一样。需要注意,一个static方法,无法访问泛型类的类型参数,所以,若要static方法需要使用泛型能力,必须使其成为泛型方法。www.zzzyk.com
 
4)限制泛型和通配符
class GenericsFoo<T extends Collection>,这样类中的泛型T只能是Collection接口的实现类,传入非Collection接口编译会出错。
class GenericsFoo<? extends Collection>,“?”代表未知类型(通配符),这个类型是实现Collection接口。<? extends 类型>表示这个类型是某个类型的子类型。
补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,