從JDK5.0開始出現(xiàn)的泛型(Generics)功能。泛型提供編譯時期的檢查,不會將對象置于某個容器而失去其類型。
http://www.onjava.com/pub/a/onjava/excerpt/javaian5_chap04/index.html
這個是JDK 1.5 的新特性。
舉個例子。
一個列表中加入3個數(shù)字,然后從列表中取出作合計的操作。
JDK 1.4 的時候
List testList = new ArrayList();
testList.add(new Integer(100));
testList.add(new Integer(200));
testList.add(new Integer(300));
int result = 0;
for(int i = 0; i < testList.size(); i ++) {
// 這里從列表中取數(shù)據(jù)時,需要強制轉(zhuǎn)換。
result += (Integer)testList.get(i).intValue();
}
System.out.println(result);
JDK 1.5 的時候
List <Integer> testList = new ArrayList <Integer> ();
// 注意,JDK1.5的 int 的 100,能夠自動的轉(zhuǎn)換成 Integer 類型。不強制要求 new Integer(100)
testList.add(100);
testList.add(200);
testList.add(300);
int result = 0;
for(int i = 0; i < testList.size(); i ++) {
// 這里從列表中取數(shù)據(jù)時,不需要強制轉(zhuǎn)換。
result += testList.get(i).intValue();
}
System.out.println(result);
posted on 2008-04-08 16:07
lk 閱讀(2091)
評論(0) 編輯 收藏 所屬分類:
j2se