In below block of code I am trying to insert 4 accounts first 2 of type aType and then 2 more of type bType.

Account[] accountToInsert = new Account[0];

Account[] accountToInsertAtype = new Account[0];
for(Integer i=0;i<2;i++) { 
    Account act = new Account();
    act.name    = 'testName';
    act.Type    = 'aType';
Account[] accountToInsertBtype = new Account[0];
for(Account act : accountToInsertAtype) {
act.type = 'bType';

insert accountToInsert;

I get the below error when I run the above code.

FATAL_ERROR System.ListException: Before Insert or Upsert list must not have two identically equal elements

the only solution I have is to repeat the same line of code again to insert the code with different account type

Above code block is just an example but in real for loop is bigger and there are plenty of fields but I need to change the value of just couple of fields and then insert the same, please suggest if we can insert more accounts without repeating the same code again.

1 Answer 1


Non-primitive data types are always passed by reference in Apex. So, you should clone the objects before modifying them for getting the copies.

Implementing as below will remove the reference to original objects.

    for(Account act : accountToInsertAtype) {
        Account newAcc = act.clone();
        newAcc.type = 'bType';
  • Thank you so much
    – gs650x
    Commented Nov 4, 2019 at 9:11

You must log in to answer this question.

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