【发布时间】:2012-02-20 01:05:25
【问题描述】:
在迭代中修改集合有时会产生异常,而有时则不会,为什么?
并发修改异常
Set<Integer> j = new HashSet<Integer>();
j.add(23);
j.add(45);
j.add(64);
int c=0;
for(Integer k: j)
{
if(c++==0)
{
j.remove(45);
}
}
System.out.println(j); // concurrent modification exception
<hr>
//works without exception
Set<Integer> j = new HashSet<Integer>();
j.add(23);
j.add(45);
j.add(64);
int c=0;
for(Integer k: j)
{
if(k==45)
{
j.remove(45);
}
}
System.out.println(j);//works without exception
【问题讨论】:
标签: java exception collections iteration