到 Google 资讯主页   
EasyJF首页   资料   源码   软件    论坛   网站    
   使用帮助    
    该信息为本站MyRSS系统缓存内容,部分图片及附件有可能无法正常使用.easyjf.comwww.javaresearch.org无关,不对该信息负责.通过http://www.javaresearch.org/article/78829.htm访问该信息的原始内容.
页面功能  【加入收藏】 【推荐给朋友】 【字体:  】 【关闭】   
java 泛型 - 类
作者:challengehope 来源:www.javaresearch.org  发布时间:2007-12-11 11:13:08.693


对类的泛型, 我们看一下例子:
public class Box<T> {
    private T t;
    
    private void add(T t) {
        this.t = t;
    }
    
    public T get() {
        return t;
    }
    
     public static void main(String[] args) {
        Box<Integer> boxInt = new Box<Integer>();
        boxInt.add(1);
        Integer intResult = boxInt.get();
        
        Box<String> boxStr = new Box<String>();
        boxStr.add("Test");
        String strResult = boxStr.get();
                
        System.out.println("Integer Result : " + intResult);
        System.out.println("String Result : " + strResult);
    }
}
运行结果:

Integer Result : 1
String Result : Test

是不是很有意思, 我们写了一个类, 但这个类的类型却不适固定的, 他即可以为String, 又可以为Integer, 可以为任意定义的类型(非primitive)。

简单解释一下, T就是type, java定义的一个泛型的概念, 即不适关键字, 也不适类, 可以适应任何类型!e.g.:
当我们传入String类型的时候, 那么T的类型就是String, 如果String strResult = boxStr.get(); 被替换成Integer strResult = boxstr.get();就会报错, 因为类型不匹配。这样的好处就是可以再代码中发现错误。


这样的代码再我们日常编码中比较少见, 我们比较常用的只是对Collection类的一些泛型使用。但是再一些框架程序中, 我们经常可以看到这样编程的影子! 如easyMock等。

 
相关文章
 
页面功能  【加入收藏】 【推荐给朋友】 【字体:  】 【关闭】   


EasyJF.com 2006 隐私政策 使用EasyJF前必读