Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.
Sets of Objects
Sets can contain sObjects among other types of elements.
Sets contain unique elements. Uniqueness of sObjects is determined
by comparing the objects’ fields. For example, if you try to
add two accounts with the same name to a set, with no other fields
set, only one sObject is added to the set.
1// Create two accounts, a1 and a2
2Account a1 = new account(name='MyAccount');
3Account a2 = new account(name='MyAccount');
4
5// Add both accounts to the new set
6Set<Account> accountSet = new Set<Account>{a1, a2};
7
8// Verify that the set only contains one item
9System.assertEquals(accountSet.size(), 1);If you add a description to one of the accounts, it is considered
unique and both accounts are added to the set.
1// Create two accounts, a1 and a2, and add a description to a2
2Account a1 = new account(name='MyAccount');
3Account a2 = new account(name='MyAccount', description='My test account');
4
5// Add both accounts to the new set
6Set<Account> accountSet = new Set<Account>{a1, a2};
7
8// Verify that the set contains two items
9System.assertEquals(accountSet.size(), 2);