Exception:
System.ListException: Before Insert or Upsert list must not have two identically equal elements
Resolution:
This exception occurs when you are trying to insert or upsert a list which is having two or more identical records. In this case we have to use set instead of list. So, that it will be overwritten because list can contain duplicates but set cannot contain duplicates.
Check this to know more about List, Set, Map.
Sample Apex Code to reproduce the issue:
List < Account > listAccounts = new List < Account >();
Account objAccount = new Account();
for ( Integer i = 0; i <= 3; i++ ) {
objAccount.Name = 'Testing ' + i + ' Account';
listAccounts.add( objAccount );
}
insert listAccounts;
Fix for the above code:
List < Account > listAccounts = new List < Account >();
for ( Integer i = 0; i <= 3; i++ ) {
Account objAccount = new Account();
objAccount.Name = 'Testing ' + i + ' Account';
listAccounts.add( objAccount );
}
insert listAccounts;