Difference between Clone and DeepClone in Apex in Salesforce

Difference between Clone and DeepClone in Apex in Salesforce

Clone:

If a list is cloned, it duplicates it and has reference.

Primitive data types are supported.

Sample Code:

Account Account1= new Account(Name='Test1');
Account Account2= new Account(Name='Test2');
List<Account> AccountList = new List<Account>{Account1, Account2};
List<Account> listDuplicate = new List<Account>();
listDuplicate = AccountList.clone();
AccountList.get(0).Name = 'Testing1';
system.debug(AccountList.get(0).Name + ',' + listDuplicate.get(0).Name);
Now AccountList.get(0).Name and listDuplicate get(0).Name will be ‘Testing1’.
listDuplicate.get(0).Name = 'Testing2';
system.debug(AccountList.get(0).Name + ',' + listDuplicate.get(0).Name);

Now AccountList.get(0).Name and listDuplicate get(0).Name will be ‘Testing2’.

Deep Clone:

If a list is DeepCloned, it duplicates and doesn’t have any reference.

Primitive data types are not supported.

Parameters:

Boolean opt_preserve_id – Whether cloned sObjects records ids are maintained.

Boolean opt_preserve_readonly_timestamps– Whether cloned sObjects records read only system fields like createdDate, LastMo

Boolean opt_preserve_autonumbe– Whether cloned sObjects records auto number fields are maintained.

Sample Code:

Account Account1= new Account(Name='Test1');
Account Account2= new Account(Name='Test2');
List<Account> AccountList = new List<Account>{Account1, Account2};
List<Account> listDuplicate = new List<Account>();
listDuplicate = AccountList.deepClone();
AccountList.get(0).Name = 'Testing1';
system.debug(AccountList.get(0).Name + ',' + listDuplicate.get(0).Name);
Now AccountList.get(0).Name will be ‘Testing1’ and listDuplicate get(0).Name will be 'Test1'.
listDuplicate.get(0).Name = 'Testing2';
system.debug(AccountList.get(0).Name + ',' + listDuplicate.get(0).Name);

Now AccountList.get(0).Name will be ‘Testing1’ and listDuplicate get(0).Name will be ‘Testing2’.

list1 = list2 is same as clone();

Leave a Reply