August 14, 2014

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.

Parameters:

Not applicable

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();

3 comments:

  1. What do you mean by "has reference"?

    Does changing the original record's values change the values in the new record as well?

    ReplyDelete
    Replies
    1. Did you go through the examples.
      "Has Reference" means the cloned record points to the original record from which it was cloned.

      Delete