+ Start a Discussion
Andy Kallio 7Andy Kallio 7 

Admin out of bounds: List index out of bounds

Another list index ouf of bounds error encountered by an admin. The other posts aren't helping me. The purpose of my code is to chain Billing Schedule records together with with a self lookup based on a Date field. This will allow me to write validations to prevent certain actions until actions on the previous Billing Schedule record have been fulfilled. 

After thinking it though, I've determined that I have to use a custom sort for sobjects. I simply followed an example in salesforce docs on how to write a wrapper class that does this, and it appears to be working fine with the test class, but I'm getting a List Index out of bounds error when try it through the UI. 

I'm stuck because alll of my system.debugs look fine. For example, if my test has 8 Billing Schedule records then I get List index out of bounds:8 but the system debugs show that I'm only counting and retrieving from the list for 0 to 8. So, can anyone see how I'm going out of bounds? 
 
public class sortBillingSchedule {

    public static void populatePrevSched(String PrjId) {
        List<Billing_Schedule__c> bss = new List<Billing_Schedule__c>();
        List<BillingScheduleWrapper> bsList = new List<BillingScheduleWrapper>();
        Integer count = 0;
        
        for(Billing_Schedule__c bs : [select Id, Billing_Date__c, Previous_Billing_Schedule__c  from Billing_Schedule__c where Project__c = :PrjId]) {
            bsList.add(new BillingScheduleWrapper(bs));
        }
        bsList.sort();
        system.debug('======bsList '+bsList);
        while(count <= bsList.size()) {
           system.debug('========== count '+count+' ============ size'+bsList.size());
            If(count > 0) {
            	Billing_Schedule__c bs1 = bsList.get(count).bs;
            	bs1.Previous_Billing_Schedule__c = bsList.get(count - 1).bs.Id;
            	bss.add(bs1);
            }
            count++;
        }
        update bss;
        
    }
}

 
Best Answer chosen by Andy Kallio 7
Lalit Mistry 21Lalit Mistry 21
Hi Andy,

Modify the condition in while loop as below
while(count < bsList.size())

That should prevent you from receiving list index out of bound error.

All Answers

Lalit Mistry 21Lalit Mistry 21
Hi Andy,

Modify the condition in while loop as below
while(count < bsList.size())

That should prevent you from receiving list index out of bound error.
This was selected as the best answer
Andy Kallio 7Andy Kallio 7
Haha! that was it...and that is why i preface all my questions on the dev board with 'Admin'!