Activity Forums Salesforce® Discussions What is the difference between these two(loop) codes? Reply To: What is the difference between these two(loop) codes?

  • Mohit

    September 23, 2016 at 6:15 am

    Hi Pranav,

    So you want difference between for loop and for each loop. As your first code for the for each loop and second code is for the for loop.

    1)We use the for each loop when we don't know the number of iteration it is going to iterate and we use for loop when we have fixed no of iteration like n size of iteration.

    2)When you want to add/remove items from the collection during iteration. This  will throw an exception that "Cannot modify a collection while it is being iterated." in Apex if you using first code but it will not thow exception when we use the second code.

    3)Perform the comparison operation between the current value or the previous or next value within the same list or separate list.It cannot be done in first code but can we achieve in second code.

    Eg:-for(Integer i =1 ;i<accountList.size()-1;i++){