[SalesForce] Cannot modify a collection while it is being iterated

Using an iterator and adding an element is not giving an error for the first example, where as the second example to add an element in the list while iterating through it gives an error.
What could be the reason that it does not give any error in the former example but gives error in the latter ?
Error throwing for second example – Cannot modify a collection while it is being iterated

Example 1:

List<Integer> addList = new List<Integer>();
addList.add(19);
addList.add(20);
addList.add(89);
addList.add(14);
Iterator<Integer> intIterator = addList.iterator();
while(intIterator.hasNext()){
    intIterator.next();
    if(intIterator.next()==2)
    {
        addList.add(1);
    }
}

Example 2:

List<Integer> addList = new List<Integer>();
addList.add(19);
addList.add(20);
addList.add(89);
addList.add(14);
for(integer i : addList){
    if(i==19){
        addList.add(1);
    }
}

Best Answer

I tried a simple experiment by changing your first example data from 2 into 20. So the code becomes:

intIterator.next();
if(intIterator.next()==20)
{
    addList.add(1);
}

Now it throws the same error as in Example 2.

So, the reason why Example 1 is not throwing error is quite simple now: it is because it NEVER really add(1) into addList, so the list is not modified.

Related Topic