当使用增强for循环迭代访问集合元素时,集合不能被改变(增删),否则会报ConcurrentModificationException异常
// 创建集合、添加元素的代码与前一个程序相同
Collection coll = new HashSet();
coll.add(new String("孙悟空"));
coll.add(new String("猪八戒"));
coll.add(new String("沙僧"));
for (Object obj : coll) {
System.out.println(obj);
if (obj.equals("孙悟空")) {
// 下面代码会引发ConcurrentModificationException异常
coll.remove(obj);
coll.add("唐僧");
System.out.println("if里:\t" + coll);
}
}
System.out.println(coll);
}