Java中泛型之类型参数(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);
 }

}

相关内容