Created
November 29, 2016 20:02
-
-
Save brianmfear/c743f212245d6dfe5fed16b494135028 to your computer and use it in GitHub Desktop.
Difference between deep and shallow clone in Apex Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@isTest class CloneExamples { | |
@isTest static void unitTest() { | |
Account a1 = new Account(Name='Test'); | |
Account a2 = a1.clone(); | |
a2.Name = 'Test 2'; | |
// Proof that a1 is not modified with shallow clone | |
System.assert(a1.Name != a2.Name); | |
Contact c1 = new Contact(Account=a1); | |
Contact c2 = c1.clone(); | |
Contact c3 = c1.clone(false, true); | |
// Proof that c1 and c2 reference same Account (shallow copy) | |
System.assert(c1.Account === c2.Account); | |
// Proof that c1 anc c3 reference different Accounts (deep copy) | |
System.assert(c1.Account !== c3.Account); | |
a1.Name = 'Test 3'; | |
// Proof that c2.Account references a1 (shallow copied) | |
System.assertEquals(a1.Name, c2.Account.Name); | |
// Proof that c3.Account does not reference a1 (deep copied) | |
System.assertNotEquals(a1.Name, c3.Account.Name); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment