zoukankan      html  css  js  c++  java
  • Java泛型类特性

    在2004年末Java推出了Java5,其中提供了对泛型方法和类的支持,也围绕着泛型推出了一下特性,本章将对Java泛型进行综合的概括

    1.泛型特性构件pre-Java 5

     1.使用Object表示泛型

        

    public class test{
       public static void main(String[]args){
         test t =new test();
    
        t.write("3");
       String val = (String)t.read();
       System.out.Println("val"); 
    } 
    } 

    当引用类型与Object相容即可

      2.基本类型的包装

       包装类(wrapper class)用于存储当对象构建时所设置的原值,是不可变的,例如int的包装类是Integer

    public class test{
       public static void main(String[]args){
         test t =new test();
    
         t.write(new Integer(3));
       Integer wrapperval = (Integer)m.read();
       int val =wrapperval.inValue();
       System.out.Println(val);
    } 
    } 

      3.使用接口类型表示泛型

        实现Comparable接口才能够作为Comparable数组被传递,仅有CompareTo方法宣称实现Comparable接口对象不是Comparable,不具有IS—A关系

          1.如果Compareable数组有两个不相容的对象,将会报出ClassCasrException异常

          2.基本类型不能作为Comparable传递,但是包装类可以,因为实现了Comparable接口

      4.数组类型的兼容

          

    class FindMaxDemo
    {
         public static Comparable findMax(Comparable[] arr){
           int maxIndex=0;
       
         for(int i=1;i<arr.length;i++){
           if(arr[i].compareTo(arr[maxIndex])>0)
                maxIndex=1;
       
       return arr[maxIndex];
    }  
    /**
    *
    */
     public static void main(String [] args){
         Shape[] sh1 ={
               new Circle(2.0),
               new Square(3.0)
    };
     String [] st1 = {"joe"};
     System.out.Println(findMax(sh1));
    }
    }  
    }        

    协变数组类型都说明了允许存储的数组类型,如果将一个不兼容的类型插入到数组,将抛出ClasscastException异常

    Java泛型成分

      1.简单的泛型类和接口

        将Comparable作为接口

      2.自动装箱拆箱

      3.带有限制的通配符

        在JAVA5中利用通配符来表示参数类型的子类(或超类):Collection<?super extends Class>

      4.泛型static方法

      5.类型限界

        将参数指定必须具有的性质,演变为

      public static<AnyType extends Comparable<AnyType>>

      6.类型擦除

        当一个擦除返回泛型方法被调用时,一些特性被自动插,如果一个泛型类不带类型参数,那么使用原始类

      7.泛型限制

        instance of检测

    在综合了泛型带来的特性后,将从泛型集合进行综合

    2.泛型类的基本定义

      

        

  • 相关阅读:
    Splunk_转发器配置_AD
    Splunk SPL 时间转换
    Splunk_索引自动清理历史数据
    Python 备查 线程池
    Splunk_SPL 排除搜索结果
    Splunk_SPL 查询时间范围
    质量的分级
    各类BOM
    Jmeter负载测试的注意事项
    MEM的面试记录
  • 原文地址:https://www.cnblogs.com/EraserHead/p/6500731.html
Copyright © 2011-2022 走看看