zoukankan      html  css  js  c++  java
  • java范型简介

    java范型简介

    一.简单认识java范型      

              经常听人说“范型”,我一直不是太明白什么叫“范型”,今天就查阅了一些文章,给我的第一感觉就是之所以在java中用范型,就是为了让一些错误在编译阶段就可以暴露出来,而不用在运行阶段才抛出异常。下面给出一个简单例子来说明。

        /** *//**
         * 没有利用范型的例子
         */
        public void example1()...{
            ArrayList array=new ArrayList();
            array.add("this is a string");
            array.add(new Integer(3));//这里可以正确添加
           
            Iterator iterator=array.iterator();
            while(iterator.hasNext())...{
                String str=(String)iterator.next();//编译时没错,但在运行时会抛出ClassCastException异常
                System.out.println(str);
            }   
        }运行以上程序,会抛出 java.lang.ClassCastException异常,而该异常是在程序运行过程中才会发现的,如果我们利用了范型,则在编译阶段就会发现异常,从而保证类型转换安全。如下面程序:    

    public void example2()...{
            ArrayList<String> array=new ArrayList<String>();
            array.add("this is a string");
            //array.add(new Integer(3));//编译时会报异常:The method add(String) in the type ArrayList<String> is not applicable for the arguments(Integer)
           
            Iterator<String> iterator=array.iterator();
            while(iterator.hasNext())...{
                String str=iterator.next();//这里就不需要进行强制类型转换
                System.out.println(str);
            }   
        }
    这样,我们在编译阶段就可以捕获可能存在地危险。

    通过以上简单例子,我们可以看出,使用java范型的好处有:

    内在的类型转换优于在外部的人工转换
    类型的匹配问题在编译阶段就可以发现,而不用在运行阶段
    二.创建自己的范型

    任何类,接口,异常,方法都可以使用范型,下面是个简单的例子,使用范型来比较两个对象的大小,两个对象必须都实现了Comparable接口。

        public <T extends Comparable> T max(T t1, T t2) ...{
             if(t1.compareTo(t2) <= 0) ...{
                return t2;
            } else ...{
                return t1;
            }
        }
    三.参考资料


    本文来自CSDN博客 http://blog.csdn.net/hbcui1984/archive/2006/10/21/1344522.aspx

  • 相关阅读:
    csv与xlsx导出
    行业报告
    How JavaScript works: an overview of the engine, the runtime, and the call stack
    CAS单点登陆/oAuth2授权登陆
    YChaos生成混沌图像
    Why数学图像生成工具
    WHY数学图形可视化工具(开源)
    WHY翻写NEHE与红龙的3D图形程序 [开源]
    四边形密铺平面
    数学图形(1.50)三曲线
  • 原文地址:https://www.cnblogs.com/kungfupanda/p/1763494.html
Copyright © 2011-2022 走看看