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
EdCodeEdCode 

What does this syntax mean: Account acct = accts[j];

Hello,

One of the lines in this code is using a kind of syntax that I do not know. See line 13:  Account acct = accts[j]
On the left of the = it is declaring the object acct of the Class Account, that is clear.
On the right of the = I do not know what it is doing, I have not used this syntax before. The object accts is a List that is declared on line 04 and [j] here is limiting the frecuency of iterations in the loop on line 14. But, I do not understand (yet) what this (= accts[j]) is doing .
@isTest
public class TestDataFactory {
    public static List<Account> createAccountsWithOpps(Integer numAccts, Integer numOppsPerAcct) {
        List<Account> accts = new List<Account>();
        
        for(Integer i=0;i<numAccts;i++) {
            Account a = new Account(Name='TestAccount' + i);
            accts.add(a);
        }
        insert accts;
        
        List<Opportunity> opps = new List<Opportunity>();
        for (Integer j=0;j<numAccts;j++) {
            Account acct = accts[j];
            // For each account just inserted, add opportunities
            for (Integer k=0;k<numOppsPerAcct;k++) {
                opps.add(new Opportunity(Name=acct.Name + ' Opportunity ' + k,
                                         StageName='Prospecting',
                                         CloseDate=System.today().addMonths(1),
                                         AccountId=acct.Id));
            }
        }
        // Insert all opportunities for all accounts.
        insert opps;
        
        return accts;
    }
}
Could you possibly explain what is = accts[j] actually doing?

Thank you very much.

 
Best Answer chosen by EdCode
PrasathPrasath
Hi Dude,

To reference an records in a list, you can follow the name of the list with the element's index position in square brackets

In Your code : accts[j] returns the account records in the jth possition.


Thanks.

All Answers

PrasathPrasath
Hi Dude,

To reference an records in a list, you can follow the name of the list with the element's index position in square brackets

In Your code : accts[j] returns the account records in the jth possition.


Thanks.
This was selected as the best answer
JaimeBidJaimeBid
It would do the same as: 

Account acct = accts.get(j);