今天在看阿里巴巴的Java开发手册时,发现在foreach 循环里进行集合元素的 remove/add 操作会出错的问题,所以记录一下。
List<String> a = new ArrayList<String>();
a.add("1");
a.add("2");
for (String temp : a) {
if ("1".equals(temp)) {
a.remove(temp);
}
}
for (String temp : a) {
System.out.println(temp);
}
判断集合元素为“1”的时候,没有问题;但判断集合元素为“2”的时候,会报“不能在对一个List进行遍历的时候将其中的元素删除掉”的异常:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at test.main(test.java:23)
正确的做法是使用 Iterator方式:
Iterator<String> it = a.iterator();
while (it.hasNext()) {
String temp = it.next();
if ("1".equals(temp)) {
it.remove();
}
}
for (String temp : a) {
System.out.println(temp);
}