function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
EUSEUS 

Index Out of bounds

I have an object that is filled from fields from another object. I created  a list of the same object type and I need to add the records to it. However it is giving me the Index out of bounds error when I add the record to the list. Here follows the code:

Line__c MELI                = new Line__c();                
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) {
             
            MELI.MB__c             = Ref__c;                
            MELI.Tx__c                = PMT.Id;                                       
            MELI.Amount__c      = PMT.Amount__c;   
            LMELI.add(i++, MELI);                                               // The error is on this line                               
                          
    }  // for PMT ends here


I would greatly appreciate any help!

Thank you!
Mike @ BlackTabMike @ BlackTab
Why are you setting two parameters when you're adding a record to a list? If you need a "key" for your list, you should probably use a Map() so you can map an interated number to a value. 
Pundareekam KudikalaPundareekam Kudikala
Plesase use below code using Map.

Line__c MELI                = new Line__c();               
Map<Line__c> LMELI  = new Map<Integer, Line__c>();

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

integer i = 0;

for (TX__c PMT : Trx) {
            
            MELI.MB__c             = Ref__c;               
            MELI.Tx__c                = PMT.Id;                                      
            MELI.Amount__c      = PMT.Amount__c;  
            LMELI.put(i++, MELI);                                               // The error is on this line                              
                         
    }  // for PMT ends here

EUSEUS
I am using two parameters as the manual says the first is the index (element one, two,  etc.) and the second one is the record being added. I need a list of the records retrieved from the other object to insert the list after the "for" ends.

Pundareekam KudikalaPundareekam Kudikala
No it is not right. If you want add record to List you have to say "LMELI.add(MELI)" No need to integer. 
EUSEUS
If you  do that it duplicates the records on the List.  I tried it. When you insert the list tells you that the list contains duplicates. I saw the logs and it always added to the list the last record read from the Select. (BTW there are no duplicates in the Select output)
Pundareekam KudikalaPundareekam Kudikala
Then you can use set