- 論壇徽章:
- 0
|
LIST是個容器接口,可以理解為動態(tài)數(shù)組,傳統(tǒng)數(shù)組必須定義好數(shù)組的個數(shù)才可以使用,而容器對象無須定義好數(shù)組下標(biāo)總數(shù),用add()方法即可添加新的成員對象,他可以添加的僅僅只能為對象,不能添加基本數(shù)據(jù)類型,容器還對應(yīng)get(),remove()方法來獲取和刪除數(shù)據(jù)成員
List可以用序號來遍歷,但通常推薦使用iterator來遍歷
Iterator itr = list.iterator();
while (itr.hasNext()) {
Object nextObj = itr.next();
}
如果要全部刪除,用clear()方法是最簡單的。
另外,Iterator也帶有remove()方法,可以在遍歷的時候,根據(jù)一定條件來進(jìn)行刪除。
示例:
import java.util.*;
public class Test {
public static void print(List list) {
Iterator itr = list.iterator();
while (itr.hasNext()) {
System.out.print(itr.next());
System.out.print(", ");
}
System.out.println();
}
public static void main(String[] args) {
List s = new ArrayList();
for (Integer i = 0; i itr = s.iterator();
while (itr.hasNext()) {
Integer i = itr.next();
if (i % 3 == 0) {
itr.remove();
}
}
print(s);
}
}
本文來自ChinaUnix博客,如果查看原文請點:http://blog.chinaunix.net/u1/41814/showart_1097241.html |
|