類型參數的形式就是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)
* 類型通配符與類型參數相結合 。這種涉及到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);
}