I've noticed some strange(?) behaviour with Lists and Maps. Below is a snippet of code:
// Query for a List of Accounts
List<Account> accountList = [SELECT Id, BillingStreet, BillingCity, BillingState, BillingPostalCode, BillingCountry FROM Account];
// Create 2 empty maps. One for old versions of records, one for new.
Map<Id, Account> oldAccMap = new Map<Id, Account>();
Map<Id, Account> newAccMap = new Map<Id, Account>();
// Populate the old map with the initial value of the records
oldAccMap.putAll(accountList );
// Manipulate the List
for (Account acc : accountList) {
acc.BillingStreet = '1-13 St Giles High St';
acc.BillingCity = 'London';
acc.BillingState = '';
acc.BillingPostalCode = 'WC2H 8LG';
acc.BillingCountry = 'United Kingdom';
}
// Populate the new map with the new value of the records
newAccMap.putAll(accountList );
So, effectively I'm querying for records, populating a Map with them, changing those records and adding them to a different map. In effect I'm trying to do what a Trigger does with new and old records.
This doesn't work though because I'm finding that the values in new and old are mirroring eachother despite being added to one list, changed and added to another List. I'm expected the Lists to have the same AccountIds, just different values.
The only way I've found to fix this is by making 2 queries.
List<Account> newAccountList = [SELECT Id, BillingStreet, BillingCity, BillingState, BillingPostalCode, BillingCountry FROM Account];
List<Account> oldAccountList = [SELECT Id, BillingStreet, BillingCity, BillingState, BillingPostalCode, BillingCountry FROM Account];
Map<Id, Account> oldAccMap = new Map<Id, Account>();
Map<Id, Account> newAccMap = new Map<Id, Account>();
oldAccMap.putAll(oldAccountList);
for (Account acc : newAccountList) {
acc.BillingStreet = '1-13 St Giles High St';
acc.BillingCity = 'London';
acc.BillingState = '';
acc.BillingPostalCode = 'WC2H 8LG';
acc.BillingCountry = 'United Kingdom';
}
newAccMap.putAll(newAccountList);
I'd have thought querying for records, adding them to a Map, changing the List, adding them to a different Map would result in two different values when the old and new maps are compared. Instead they're the same.
I hope I'm making sense.
So my question is, is this behaviour what's to be expected? It seems odd to me.