import java.util.*;
public class Test2 {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("abc");
list.add("java");
list.add("java");
list.add("bcd");
list.add("java");
list.add("java");
sop(list);
removeList2(list);
sop(list);
}
public static void sop(Object obj) {
System.out.println(obj);
}
//方法一:
public static void removeList1(List<String> list) {
for (int i = 0; i < list.size(); i++) {
if ("java".equals(list.get(i))) {
list.remove(i);
--i;// 删除了元素,迭代的下标也跟着改变
}
}
}
// 方法二:
public static void removeList2(List<String> list) {
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String str = iterator.next();
if ("java".equals(str)) {
iterator.remove();
}
}
}
}
打印结果:
abc bcd |