Apex Maps and Sets Example
| Account a = new Account(Name = 'Foo'); | |
| // not recommended! | |
| Map<Account, String> stringsByAccounts = new Map<Account, String>(); | |
| Set<Account> accountSet = new Set<Account>{}; | |
| stringsByAccounts.put(a, 'Bar'); | |
| accountSet.add(a); | |
| // things are OK as long as you don't mutate 'a' | |
| System.assertEquals('Bar', stringsByAccounts.get(a)); | |
| System.assertEquals(true, accountSet.contains(a)); | |
| // key mutation | |
| a.Name = 'Bar'; | |
| // Map value inaccessible | |
| System.assertEquals(null, stringsByAccounts.get(a)); | |
| // Set contains doesn't work | |
| System.assertEquals(false, accountSet.contains(a)); | |
| // ... even though the it's still in the set | |
| System.assertEquals(1, accountSet.size()); | |
| // if we flip back, everything works again! | |
| a.Name = 'Foo'; | |
| System.assertEquals('Bar', stringsByAccounts.get(a)); | |
| System.assertEquals(true, accountSet.contains(a)); | |
| // 'a2' has the same field values as 'a' | |
| Account a2 = new Account(Name = 'Foo'); | |
| System.assertEquals(a,a2); | |
| System.assertEquals(System.hashCode(a),System.hashCode(a2)); | |
| // Maps and Sets can't distinguish 'a' vs 'a2' | |
| System.assertEquals('Bar', stringsByAccounts.get(a2)); | |
| System.assert(accountSet.contains(a2)); | |
| // putting a value for 'a2' into the map overwrites 'a' value 'Bar' | |
| stringsByAccounts.put(a2,'BarBar'); | |
| System.assertEquals('BarBar', stringsByAccounts.get(a)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment