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
Pratik KumarPratik Kumar 

Please let me know what is the issue with the following code to insert a List<Account>

On executing the following code, an error message pops up saying, 'System.ListException: Before Insert or Update list must not have two identically equal elements'


String n;
Account tempac = new Account();
List<Account> ac = new List<Account>();
for (Integer i = 0; i < 10; i++){
    n = 'TryAccount' + i;
    tempac.Name = n;
    ac.add(tempac);
    System.debug('Account Contect is::: ' +ac[i]); //Checkpoint 1
}

//System.debug('This is the result:::: ' +ac); // Checkpoint 2
insert ac;


Checkpoint 1 outputs value as expected i.e. TryAccount0, TryAccount1 and so on
But
Checkpoint 2 gives all identical valuses as the output i.e. TryAccount9, TryAccount9, TryAccount9, and so on.
Best Answer chosen by Pratik Kumar
Amit Chaudhary 8Amit Chaudhary 8
Issue is coming because you are trying to add same object again and again in list.

Please try to update your code like below
String n;
List<Account> ac = new List<Account>();
for (Integer i = 0; i < 10; i++)
{
	Account tempac = new Account();
    n = 'TryAccount' + i;
    tempac.Name = n;
    ac.add(tempac);
    System.debug('Account Contect is::: ' +ac[i]); //Checkpoint 1
}
//System.debug('This is the result:::: ' +ac); // Checkpoint 2
insert ac;

Let us  know if this will help you
 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Issue is coming because you are trying to add same object again and again in list.

Please try to update your code like below
String n;
List<Account> ac = new List<Account>();
for (Integer i = 0; i < 10; i++)
{
	Account tempac = new Account();
    n = 'TryAccount' + i;
    tempac.Name = n;
    ac.add(tempac);
    System.debug('Account Contect is::: ' +ac[i]); //Checkpoint 1
}
//System.debug('This is the result:::: ' +ac); // Checkpoint 2
insert ac;

Let us  know if this will help you
 
This was selected as the best answer
Pratik KumarPratik Kumar
Thanks Amit. It worked. It was so silly of me.