閱讀771 返回首頁    go 搜狐


java中泛型學習2之類型參數(T)


類型參數的形式就是List<T> lst。看測試代碼:


package cn.xy.test;

import java.util.ArrayList;
import java.util.Collection;

public class Test
{


 /**
  * 該方法使用的隻能傳Object類型的collection而不能傳Object的子類,會產生編譯錯誤
  * 因為String是Object的子類而List<String>不是List<Object>的子類
  */
 public static void copyArraytoCollection(Object[] objs, Collection<Object> cobjs)
 {
  for (Object o : objs)
  {
   cobjs.add(o);
  }
 }

 /**
  * 類型參數的使用
  */
 public static <T> void copyArraytoCollection2(T[ ] objs, Collection<T> cobjs)
 {
  for (T o : objs)
  {
   cobjs.add(o);
  }
 }

 /**
  * 類型通配符與類型參數相結合 。這種涉及到add元素的方法僅僅用類型通配符做不了,因為如List<?> lst,lst不能調用add方法
  * 設置?的上限,?必須是T的子類或者是T本身
  */
 public static <T> void copyCollectiontoCollection(Collection<T> c1, Collection<? extends T> c2)
 {
  for (T o : c2)
  {
   c1.add(o);
  }
 }

 /**
  * 類型通配符與類型參數相結合。 這種涉及到add元素的方法僅僅用類型通配符做不了,因為如List<?> lst,lst不能調用add方法
  * 設置?的下限,?必須是T的父類或者是T本身
  */
 public static <T> void copyCollectiontoCollection2(Collection<T> c1, Collection<? super T> c2)
 {
  for (T o : c1)
  {
   c2.add(o);
  }
 }

 

 public static void main(String[] args)
 {
  // 數組初始化
  Object[] oArray = new Object[100];
  String[] sArray = new String[100];
  Number[] nArray = new Number[100];

  // 容器初始化
  Collection<Object> cObject = new ArrayList<Object>();
  Collection<String> cString = new ArrayList<String>();
  Collection<Number> cNumber = new ArrayList<Number>();
  Collection<Integer> cInteger = new ArrayList<Integer>();

  // 方法調用
  copyArraytoCollection(oArray, cObject);
  // copyArraytoCollection(sArray,cString);

  copyArraytoCollection2(oArray, cObject);
  copyArraytoCollection2(sArray, cString);
  copyArraytoCollection2(nArray, cNumber);

  copyCollectiontoCollection(cNumber, cInteger);
  copyCollectiontoCollection2(cInteger, cNumber);
 }

}

 

 

最後更新:2017-04-03 07:57:27

  上一篇:go Oracle中的number類型
  下一篇:go 數據庫默認端口和驅動總結