- 执行时候返回的结果是什么 ?
List<String> aa = new ArrayList<String>();
aa.add("F1");
aa.add("F2");
aa.add("F3");
for (String temp : aa) {
if ("F3".equals(temp)) {
aa.remove(temp);
}
}
for (String temp : aa){
System.out.println(temp);
}
解答:Exception in thread "main" java.util.ConcurrentModificationException
在对集合迭代的时候,如果同时对其进行修改就会抛出java.util.ConcurrentModificationException
异常;
- 下面程序的运行结果()
List<String> aa = new ArrayList<String>();
aa.add("F1");
aa.add("F2");
aa.add("F3");
for (String temp : aa) {
if ("F3".equals(temp)) {
aa.remove(temp);
}
}
for (String temp : aa){
System.out.println(temp);
}
Java集合中有一种被称为fail-fast的错误机制,当多线程对集合进行操作时(一个线程使用迭代器遍历集合;另一个线程修改集合内容)会抛出ConcurrentModificationException异常。
就这么说吧,对于集合的三种遍历方式删除:
1.普通for循环:可以删除
注意每次删除之后索引要–
2.Iterator遍历:可以删除
不过要使用Iterator类中的remove方法,如果用List中的remove方法会报错
3.增强for循环foreach:不能删除
强制用List中的remove方法会报错