[SalesForce] List index out of bounds: 2

i hv a list. i am iterating over the elements of list using for loop.
if element is null i hv to create record. Below is my code –

for(Integer i=0; i < 3; i++){
      //split 1 calculation
            if(i==0 && shed.Sales_Rep_1__c != null){
                if(sp[i] != null)toDeletesplits.add(sp[i]);
                sp[i] = split.clone();
                sp[i].Sales_Rep__c  = shed.Sales_Rep_1__c;
                sp[i].Amount_LC__c  = percentRemain * shed.Revenue_LC__c  * .01;
                sp[i].Amount_USD__c = percentRemain * shed.Revenue_USD__c * .01;
                toInsertsplits.add(sp[i]);

            }
            if(i==0 && shed.Sales_Rep_1__c == null)
                if(sp[i] != null)toDeletesplits.add(sp[i]);

But it is throwing me List index out of bounds: 2 error at line 4 from top as i hv only 2 elements in my list. thats why i want to check if third element is not there i want to create a record. Please guide.How can i check at particular position of list element is there or not ?

Best Answer

Replace for(Integer i=0; i < 3; i++) with for(Integer i=0; i < sp.size(); i++)

You should not hardcode the list as there may not be element at the hardcoded position.

You can use this kind of approach as well:

List<String> sp = new List<String>{'a','b','c','d'};
for(Integer i=0; i < sp.size() && i < 3; i++)
     System.debug(' @@@@ ele: '+sp[i]);
Related Topic