Modifying a set over iteration sometimes creates an exception, and other times it doesn’t, why?
concurrent modification exception
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
From the JavaDocs for
HashSet:(The highlighting is mine.)