0

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 ?

1 Answer 1

4

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]);
4
  • yes i was using this only.But i can have max 3 split records. when i was using this, how can i create 3rd record. I want to check if there is any record at 3rd position or not. If not i want to create a new record. Please help
    – user12051
    Mar 18, 2015 at 9:03
  • @user12051 updated my answer.
    – Ashwani
    Mar 18, 2015 at 9:08
  • yes i got it what u r saying but i know i will have 3 records only so i am harcoding. i want to check at a particular position element is there or not. If not i want to create it. Kindly help me I stuck.
    – user12051
    Mar 18, 2015 at 9:16
  • @user12051 In list element are always have elements in series there won't be element on index 1,4,7 they will be on 0,1,2. So you can always check size of list and check if the position you are trying to get is not greater the size()-1.
    – Ashwani
    Mar 18, 2015 at 9:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .