1

I'm working on a class thats outside the normal trigger set up and used as part of an integration.

I'm looking to have two list or maps, one that contains the records data pre update. The second containing the records with the updated data. My own version of old and new list/map.

A simple example of the code and issue:

 List<Account> accListOne = [SELECT name, Email__c 
                            FROM Account 
                            WHERE Email__c != null  LIMIT 1]; 
system.debug('*** PRE UPDATE accListOne *** ' + accListOne );
system.debug('*** PRE UPDATE accListOne - email *** ' + accListOne[0].Email__c );

List<Account> accListTwo = new List<Account>(accListOne);
system.debug('*** PRE UPDATE accListTwo *** ' + accListTwo );
system.debug('*** PRE UPDATE accListTwo - email *** ' + accListTwo[0].Email__c );

for(account a : accListOne) {
  a.Email__c = 'NewTestEmail@testEmail.test';
}

system.debug('*** POST UPDATE accListOne *** ' + accListOne );
system.debug('*** POST UPDATE accListOne - email *** ' + accListOne[0].Email__c );

system.debug('*** POST UPDATE accListTwo *** ' + accListTwo );
system.debug('*** POST UPDATE accListTwo - email *** ' + accListTwo[0].Email__c );

enter image description here

As you can see above when I perform the update on the record the email is being updated in both lists.

Whats the best way to stop this happening so the update only appears in accListTwo?

Thanks

2

Objects are passed by reference, which means that two variables can refer to the same place in memory. You can read a much longer explanation here.

As a simple example:

Account a = new Account(Name='Demo');
Account b = a;
b.Name = 'Demo 2';
System.debug(a.Name); // Demo 2

To fix this, you must create all new objects. For Lists, we have the deepClone method:

List<Account> accListOne = [SELECT name, Email__c 
                            FROM Account 
                            WHERE Email__c != null  LIMIT 1]; 
List<Account> accListTwo = accListOne.deepClone(true, true, true);

At this point, changes to records in accListTwo and accListOne will no longer affect each other.

1
  • Perfect! Thanks for your help, and for the link to explanation Jan 15 at 0:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.