+ Start a Discussion
EUSEUS 

Do List indexes actually work within "For" statements from a SELECT?

I am trying to build a List of records from a List of other objects. Afterwards I need to insert the new List created. However I get the error List Index out of bounds. Here follows the code:

             
List<Line__c> LMELI  = new List<Line__c>();

List<TX__c> Trx     = [SELECT  Id,  Amount__c
                                      FROM TX__c

integer i = 0;

for (TX__c PMT : Trx) {
            
            LMELI[i].MB__c                  = Ref__c;            //  I get the error  LIST INDEX out of bounds (0)      
            LMELI[i].Tx__c                     = PMT.Id;                                      
            LMELI[i++].Amount__c      = PMT.Amount__c;  
                        
    }  // for PMT ends here

   INSERT LMELI;
Best Answer chosen by EUS
Eli Flores, SFDC DevEli Flores, SFDC Dev
List<> just creates a container for the all the elements, it doesn't have any elements in it. You have to create manually create those: Your for loop should look like  (uninteresting stuff omittted)

For (..){
       Line__c newLine = new Line__c();
       newLine.MB__c = Ref__c;
       ....
      LMELI.add(newLine);
}
insert LMELI;    
      

All Answers

SFDC_DevloperSFDC_Devloper
Hi,

Make sure that the list is not empty before accessing it:

List<Line__c> LMELI  =[SELECT Id,MB__c,Tx__c,Amount__c from Line__c Limit 10];

List<TX__c> Trx     = [SELECT  Id,  Amount__c FROM TX__c  Limit 10];
integer i = 0;

for (TX__c PMT : Trx)
   {
            if(LMELI.size()> 0)
               {
                LMELI[i].MB__c = Ref__c;          
                LMELI[i].Tx__c = PMT.Id;                                     
                LMELI[i++].Amount__c= PMT.Amount__c; 
               }    
    }  // for PMT ends here

INSERT LMELI;


Thanks,
Rockzz


EUSEUS
Hi,  the Line List  is empty.  I am creating it from scratch. (List<Line__c> LMELI  = new List<Line__c>();) So, I know I need to use the first index (0) to insert  the records. Is it a bug that APEX has or a limitation to create lists from scratch ?
Eli Flores, SFDC DevEli Flores, SFDC Dev
List<> just creates a container for the all the elements, it doesn't have any elements in it. You have to create manually create those: Your for loop should look like  (uninteresting stuff omittted)

For (..){
       Line__c newLine = new Line__c();
       newLine.MB__c = Ref__c;
       ....
      LMELI.add(newLine);
}
insert LMELI;    
      
This was selected as the best answer
EUSEUS
I had figured it out before and fixed it exactly the way you suggested DevArrah.  Thanks!