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范型的好处有:

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

二.创建自己的范型

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

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

    }

三.参考资料

1.java 范型攻略篇

原文地址:https://www.cnblogs.com/hehe520/p/6330282.html