When I run the below code, I get this error:

System.ListException: List index out of bounds


public with Sharing class EngageDeltaController {

    public static Engage__c[] getDelta() {

        Engage__c[] x = [SELECT Name, ID,Score__c,CreatedDate,Account_ID__c,Delta__c FROM    Engage__c ];
            for(Integer i=0,j=0; i<= x.size();i++)
                if(x[i].Account_ID__c == x[i+1].Account_ID__c)
                    x[i].Delta__c = x[i+1].Score__c-x[i].Score__c;        

                else system.debug('nothing found');
        return x;

  • 1
    You'll need an "order by" in the query if you are aiming to compare adjacent items to achieve reliable ordering. – Keith C Aug 24 '16 at 20:56

Not sure why you incorporated j at all... You're getting this error because, when i == x.size(), and you try to get x[i], your index is indeed out of bounds. Even when i == x.size() - 1, you are referencing x[i+1] with the same issue. A more typical loop might be:

for (i = 1; i < x.size(); i++)
    Engage__c record1 = x[i-1];
    Engage__c record2 = x[i];
    // logic here

Or alternatively:

for (i = 0; i < x.size() - 1; i++)
    Engage__c record1 = x[i];
    Engage__c record2 = x[i + 1];
    // logic here

Here's how the indices work:

List - [ 'a', 'b', 'c', 'd', 'e' ]
Index -   0    1    2    3    4

Notice that the size of the list is 5, but the highest index is 4. If you're using i+1 as an index, the highest value you can use for i is 3.

If you're trying to get each pair, you can either use [i, i+1] and values of i 0-3, or [i-1, i] and values of i 1-4. I prefer the latter because it allows you to use a more concise loop syntax.


try using i< x.size() instead of i<= x.size().

List element counting always starts with 0.

  • That's not a complete fix, and it's already been answered and removed. – Adrian Larson Aug 24 '16 at 21:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.