function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Govind BangaloreGovind Bangalore 

Cannot modify a collection while it is being iterated + apex error

Hello Peers,
can someone help me to resolve this issue.I am not able to understand how to fix it.
Thanks In Advance
Best Answer chosen by Govind Bangalore
ravi soniravi soni
hi salesforce Traning 2,
I have faced the same issue. below is dummy example for good understanding.
list<Account> lstAcc = [SELECT Id,Name From Account];
for(Account acc : lstAcc){
    lstAcc.remove(0);
}
//Error => System.FinalException: Cannot modify a collection while it is being iterated.
Solution : => 
list<Account> lstAcc = [SELECT Id,Name From Account];

for(Account acc : [SELECT Id,Name From Account]){
    lstAcc.remove(0);
}
if you stuck in this problam then you can store list in separate variable called x and for loop use separate variable called Y  and simply modify the x list.
your problam will be resolved.
don't forget to mark it as best answer.
Thank you


 

All Answers

mukesh guptamukesh gupta
Hi Training,

The problem is that you are modifying a list of records that you are iterating over.  Lets take the following snippet from your code as an example

WRONG
List<account> ls = [
     select name
     from account
     where name = :aname
];

for (account ac : ls) {
     ac.Name = aname;
     ac.Phone = aphone;
     ac.BillingCity = acity;
     ls.add(ac); ******************************this line update ls that's using for iteration ,                   ************************************************ we should not update this list
}

Above code should be like this :-

CORRECT
List<account> ls = [
     select name
     from account
     where name = :aname
];

for (account ac : ls) {
     ac.Name = aname;
     ac.Phone = aphone;
     ac.BillingCity = acity;
}

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh
ravi soniravi soni
hi salesforce Traning 2,
I have faced the same issue. below is dummy example for good understanding.
list<Account> lstAcc = [SELECT Id,Name From Account];
for(Account acc : lstAcc){
    lstAcc.remove(0);
}
//Error => System.FinalException: Cannot modify a collection while it is being iterated.
Solution : => 
list<Account> lstAcc = [SELECT Id,Name From Account];

for(Account acc : [SELECT Id,Name From Account]){
    lstAcc.remove(0);
}
if you stuck in this problam then you can store list in separate variable called x and for loop use separate variable called Y  and simply modify the x list.
your problam will be resolved.
don't forget to mark it as best answer.
Thank you


 
This was selected as the best answer