Set Collection of sObject

Set –  A set is an unordered collection of elements that do not contain any duplicates.
Set elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.
Sets can contain collections that can be nested within one another. For example, you can have a set of lists of sets of Integers.
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.

// Create two accounts, a1 and a2
Account a1 = new account(name='MyAccount');
Account a2 = new account(name='MyAccount');

// Add both accounts to the new set
Set<Account> accountSet = new Set<Account>{a1, a2};

// Verify that the set only contains one item
System.assertEquals(accountSet.size(), 1);

If you add value for one more field of one account, it is consider unique and both accounts are added to set. like below code –

// Create two accounts, a1 and a2
Account a1 = new account(name='MyAccount');
Contact c1 = new Contact(firstname='MyAccount');

// Add both accounts to the new set
Set<sObject> accountSet = new Set<sObject>{a1, c1};

// Verify that the set only contains one item
System.debug('Set Size is = '+accountSet.size());

// Verify that the set only contains one item

System.assertEquals(accountSet.size(), 2);

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s