---
schema_version: "1"
id: f1704c29e23ab392332423cadf609e0a77fe57429a42539f81ca74786ea7f47a
title: Sets of Objects
collection: legacydeveloper
version: current
locale: en-us
portal_url: https://docs.salesforce.com/legacydeveloper/current/en-us/apexcode/apex_set_sobject.md
canonical_url: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_set_sobject.htm
source_site: developer.salesforce.com
content_type: documentation
content_hash: 67de86bbf36c2cf9cab688a398bcc26eb8e5aacbae9d1062bdcfb1b857a91e6f
description: Sets can contain sObjects among other types of elements.
---
# 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.

// 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
Assert.areEqual(1, accountSet.size());

If you add a description to one of the accounts, it is considered unique and both accounts are added to the set.

// Create two accounts, a1 and a2, and add a description to a2
Account a1 = new account(name='MyAccount');
Account a2 = new account(name='MyAccount', description='My test account');

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

// Verify that the set contains two items
Assert.areEqual(2, accountSet.size());

![Warning](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/images/icon_note_warning.png)

#### Warning

If set elements are objects, and these objects change after being added to the collection, they won’t be found anymore when using, for example, the contains or containsAll methods, because of changed field values.