Sub topic 15
References, clone, and deepClone
This chapter assumes you know how to declare Lists, Sets, and Maps, and that you have worked with SObjects such as Account and Contact. It explains what happens when you assign a collection to another variable, how to make copies, and where copies stop being independent.
Variables hold references
In Apex, a collection variable does not contain the elements. It holds a reference, which is a pointer to a collection object stored on the heap. Assigning one variable to another copies the reference, not the collection.
List<String> original = new List<String>{'a', 'b'};
List<String> alias = original;
alias.add('c');
System.debug(original); // (a, b, c)
System.debug(original == alias); // trueBoth variables point to the same List. A change through either name is visible through the other. The same applies to Sets and Maps, and to objects of your own classes and to SObjects.
This also applies when you pass a collection to a method. The method receives a copy of the reference, so it can change the caller's collection.
public class ReferenceDemo {
public static void addDefault(List<String> items) {
items.add('default');
}
public static void reassign(List<String> items) {
items = new List<String>{'new'}; // only changes the local variable
}
public static void run() {
List<String> values = new List<String>{'x'};
addDefault(values);
System.debug(values); // (x, default)
reassign(values);
System.debug(values); // (x, default)
}
}addDefault modifies the shared object, so the caller sees the change. reassign points its own parameter at a new List, which leaves the caller's variable untouched.
Making a shallow copy
To get an independent collection, copy it. Each type offers two ways: the clone() method and the copy constructor.
List<Integer> a = new List<Integer>{1, 2, 3};
List<Integer> b = a.clone();
List<Integer> c = new List<Integer>(a);
b.add(4);
c.remove(0);
System.debug(a); // (1, 2, 3)
System.debug(b); // (1, 2, 3, 4)
System.debug(c); // (2, 3)The same works for Sets and Maps.
Set<String> s1 = new Set<String>{'x', 'y'};
Set<String> s2 = s1.clone();
s2.add('z');
Map<String, Integer> m1 = new Map<String, Integer>{'one' => 1};
Map<String, Integer> m2 = m1.clone();
m2.put('two', 2);
System.debug(s1.size()); // 2
System.debug(m1.size()); // 1For collections of primitives such as String, Integer, and Id, a shallow copy is all you need. Primitives are immutable values, so there is nothing shared that could be changed.
Why a shallow copy is not always enough
A shallow copy creates a new collection but copies the references stored in it. If the elements are objects, such as SObjects or instances of your own classes, the original and the copy hold references to the same element objects.
List<Account> accts = new List<Account>{
new Account(Name = 'Acme'),
new Account(Name = 'Globex')
};
List<Account> shallow = accts.clone();
shallow[0].Name = 'Acme Renamed';
System.debug(accts[0].Name); // Acme Renamed
shallow.add(new Account(Name = 'Initech'));
System.debug(accts.size()); // 2Two different things happen here:
- Adding or removing elements in the copy does not affect the original, because the two Lists are separate objects.
- Editing a field on an element changes the original too, because both Lists point to the same Account.
The diagram shows this.
deepClone for Lists of SObjects
When you need independent records, use deepClone(). It is available on Lists of SObjects. It creates a new List and also a copy of each SObject in it.
List<Account> accts = new List<Account>{
new Account(Name = 'Acme'),
new Account(Name = 'Globex')
};
List<Account> deep = accts.deepClone();
deep[0].Name = 'Acme Renamed';
System.debug(accts[0].Name); // Acme
System.debug(deep[0].Name); // Acme RenameddeepClone takes optional Boolean arguments: deepClone(preserveId, preserveReadonlyTimestamps, preserveAutonumber). With no arguments, the copied records do not keep their Id. That makes the default useful for the common task of duplicating records to insert as new ones.
List<Account> existing = [SELECT Id, Name, Industry FROM Account LIMIT 5];
// New records without Ids, ready to insert as copies.
List<Account> copies = existing.deepClone();
for (Account a : copies) {
a.Name = a.Name + ' (Copy)';
}
insert copies;
// Same copies but keeping the original Ids, for in-memory edits only.
List<Account> withIds = existing.deepClone(true);SObject records have their own clone() method with the same options: clone(preserveId, isDeepClone, preserveReadonlyTimestamps, preserveAutonumber). For a single record, acct.clone(false, true) produces a copy without its Id.
Copying Maps of SObjects
Map has deepClone() too, but only when its values are SObjects. It copies each value record and returns a new Map. Calling clone() on a Map of SObjects gives a shallow copy, so the values are still shared.
Map<Id, Account> byId = new Map<Id, Account>(
[SELECT Id, Name FROM Account LIMIT 5]
);
Map<Id, Account> shallowMap = byId.clone();
Map<Id, Account> deepMap = byId.deepClone();
for (Account a : byId.values()) {
a.Name = 'Changed';
break;
}
// shallowMap sees the change on that record; deepMap does not.Sets do not have deepClone(). Set elements should not be changed after being added, so there is little to protect.
Collections inside collections
deepClone does not reach into nested collections. A Map<Id, List<Contact>> copied with clone() shares every inner List. To get independent inner Lists, copy each one yourself.
Map<Id, List<Contact>> grouped = new Map<Id, List<Contact>>();
// ... grouped is filled elsewhere ...
Map<Id, List<Contact>> copy = new Map<Id, List<Contact>>();
for (Id key : grouped.keySet()) {
copy.put(key, grouped.get(key).deepClone());
}Here each inner List is deep cloned, so both the Lists and their Contacts are independent. Use clone() instead of deepClone() in the loop if you want new Lists but shared records. The rule is that you copy every level you intend to change.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| `b = a` and then changing `b` | `a` changes as well | Use `a.clone()` or `new List<T>(a)` |
| Using `clone()` and editing record fields | Original records change | Use `deepClone()` |
| Updating records from default `deepClone()` | Fails because Ids are cleared | Pass `true` for `preserveId` |
| Copying only the outer Map of a Map of Lists | Inner Lists shared | Copy each inner List in a loop |
| Expecting a method to reassign the caller's variable | Caller's variable unchanged | Return the new collection |
Sharing is sometimes what you want. Building a Map from a List with new Map<Id, Account>(accounts) keeps references to the same records, so editing byId.get(id) edits the record in your original List. This is often useful before a single update, and it is why you do not need to rebuild the List afterwards.
Exercise
A trigger handler runs List<Account> backup = accounts.clone(); and then sets Industry = 'Retail' on every record in accounts. It expects backup to hold the old industries. What actually happens, and how do you fix it?
Show answer
clone() makes a shallow copy. The backup List is a new object, but it holds references to the same Account records, so the Industry change is visible through backup as well. Use accounts.deepClone(true) to copy the records themselves. Pass true to keep the Ids if you want to compare or update the backups later.
Exercise
You copy a Map<Id, List<Contact>> with clone(), then add a Contact to one of the inner Lists of the copy. Does the original Map change? Why?
Show answer
Yes. clone() copies only the outer Map. Both Maps hold references to the same inner Lists, so adding a Contact through the copy also adds it in the original. Build a new Map and put a copy of each inner List (for example list.clone() or list.deepClone()) to separate them.