Java Generic(-) 爲何須要使用泛型

泛型:參數化類型,即因爲類型的不肯定性,咱們能夠引入一個參數來表示代替某種類型.數組

爲何須要泛型呢?看如下例子:ide

  
  
  
  
  1. /** 
  2.  *  
  3.  */ 
  4. package com.skywares.generic; 
  5.  
  6. /** 
  7.  * @author Administrator 
  8.  *  
  9.  */ 
  10. public class PrintArray { 
  11.  
  12.     /** 
  13.      * @param args 
  14.      */ 
  15.     public static void main(String[] args) { 
  16.  
  17.         Integer[] iray = { 1234 }; 
  18.         Character[] cray = { 'a''b''c''d' }; 
  19.  
  20.         printMe(iray); 
  21.         printMe(cray); 
  22.  
  23.     } 
  24.  
  25.     private static void printMe(Character[] cray) { 
  26.         for (Character x : cray) { 
  27.             System.out.println(x); 
  28.         } 
  29.     } 
  30.  
  31.     private static void printMe(Integer[] iray) { 
  32.         for (Integer x : iray) { 
  33.             System.out.println(x); 
  34.         } 
  35.     } 
  36.  

     在這段程序中,咱們有兩個重載的方法printMe,一個須要的參數是Character[],另外一個是Integer[],具體的方法處理部分基本一致,只是只爲數組中的元素類型不一樣,咱們就須要爲它定義兩個方法來處理,試想一下,若是未來要增長一個打印String, Double, 某一用戶自定義類型的Java對象數據時,咱們豈不是要n屢次地去重載printMe(Type  array)這個方法.spa

    試想一下,若是咱們可以一種類型去表明要傳入地數組中的元素,就像一個參數去表明未來要傳遞過來的值,那麼,咱們就能夠不用去重載這個printMe()方法了.因此參數化類型(泛型)就應運而生了.對象

    如下是使用泛型方法改造後的代碼:string

  
  
  
  
  1. /** 
  2.  *  
  3.  */ 
  4. package com.skywares.generic; 
  5.  
  6. /** 
  7.  * @author Administrator 
  8.  * 
  9.  */ 
  10. public class PrintArrayUseGeneric<T> { 
  11.  
  12.     /** 
  13.      * @param args 
  14.      */ 
  15.     public static void main(String[] args) { 
  16.         // TODO Auto-generated method stub 
  17.         Integer[] iray = { 1234 }; 
  18.         Character[] cray = { 'a''b''c''d' }; 
  19.         String[] sray = {"ab","bc","cd"}; 
  20.          
  21.         printMe(iray); 
  22.         printMe(cray); 
  23.         printMe(sray); 
  24.     } 
  25.      
  26.     private static <E> void printMe(E[] tray) 
  27.     { 
  28.         for(E e : tray) 
  29.         { 
  30.             System.out.print(e); 
  31.         } 
  32.         System.out.println(); 
  33.     } 
  34.  

     若是未來有用戶自定義的類要進行打印的話,只須要這個類實現自已的toString()方法便可.可擴展性極好.it

相關文章
相關標籤/搜索