泛型:參數化類型,即因爲類型的不肯定性,咱們能夠引入一個參數來表示代替某種類型.數組
爲何須要泛型呢?看如下例子:ide
- /**
- *
- */
- package com.skywares.generic;
- /**
- * @author Administrator
- *
- */
- public class PrintArray {
- /**
- * @param args
- */
- public static void main(String[] args) {
- Integer[] iray = { 1, 2, 3, 4 };
- Character[] cray = { 'a', 'b', 'c', 'd' };
- printMe(iray);
- printMe(cray);
- }
- private static void printMe(Character[] cray) {
- for (Character x : cray) {
- System.out.println(x);
- }
- }
- private static void printMe(Integer[] iray) {
- for (Integer x : iray) {
- System.out.println(x);
- }
- }
- }
在這段程序中,咱們有兩個重載的方法printMe,一個須要的參數是Character[],另外一個是Integer[],具體的方法處理部分基本一致,只是只爲數組中的元素類型不一樣,咱們就須要爲它定義兩個方法來處理,試想一下,若是未來要增長一個打印String, Double, 某一用戶自定義類型的Java對象數據時,咱們豈不是要n屢次地去重載printMe(Type array)這個方法.spa
試想一下,若是咱們可以一種類型去表明要傳入地數組中的元素,就像一個參數去表明未來要傳遞過來的值,那麼,咱們就能夠不用去重載這個printMe()方法了.因此參數化類型(泛型)就應運而生了.對象
如下是使用泛型方法改造後的代碼:string
- /**
- *
- */
- package com.skywares.generic;
- /**
- * @author Administrator
- *
- */
- public class PrintArrayUseGeneric<T> {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Integer[] iray = { 1, 2, 3, 4 };
- Character[] cray = { 'a', 'b', 'c', 'd' };
- String[] sray = {"ab","bc","cd"};
- printMe(iray);
- printMe(cray);
- printMe(sray);
- }
- private static <E> void printMe(E[] tray)
- {
- for(E e : tray)
- {
- System.out.print(e);
- }
- System.out.println();
- }
- }
若是未來有用戶自定義的類要進行打印的話,只須要這個類實現自已的toString()方法便可.可擴展性極好.it