用foreach遍历时,在remove,add方法经常会报异常:Process finished with exit code 1
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list .add("a");
list .add("b");
list .add("c");
for (String temp : list ) {
//这里如果移除list集合的第一个或者最后一个元素则会报错,移除中间的“b”是不会报错的
if ("a".equals(temp)) {
list .remove(temp);
}
}
System.out.println(list );
}
所以,当我们需要满足条件都移除时,这种方式肯定会出问题。故此,我们可以尝试用迭代器iterator来达到需要移除的目的:
public static void main(String[] args) {
List<String> list = new ArrayList<String>(); //需要遍历的list
list.add("a");
list.add("b");
list.add("c");
Iterator it = list.iterator();
while (it.hasNext()) {
Object o = it.next(); //当前遍历对象
if ("a".equals(o)) {
it.remove(); //删除或修改都可以
}
}
System.out.println(list);
}