Sets

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. For example, the following table represents a set of strings, that uses city names:

'San Francisco' 'New York' 'Paris' 'Tokyo'

Sets can contain collections that can be nested within one another. For example, you can have a set of lists of sets of Integers. A set can contain up to four levels of nested collections inside it.

To declare a set, use the Set keyword followed by the primitive data type name within <> characters. For example:
new Set<String>()

The following are ways to declare and populate a set:

Set<String> s1 = new Set<String>{'a', 'b + c'}; // Defines a new set with two elements
Set<String> s2 = new Set<String>(s1); // Defines a new set that contains the 
                                     // elements of the set created in the previous step

To access elements in a set, use the system methods provided by Apex. For example:

Set<Integer> s = new Set<Integer>(); // Define a new set
s.add(1);                            // Add an element to the set
System.assert(s.contains(1));        // Assert that the set contains an element
s.remove(1);                         // Remove the element from the set
Uniqueness of non-primitive objects is determined by comparing the objects’ fields, except for objects of user-defined types. For example, if you try to add two accounts with the same name to a set, only one is added.
// 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);
However, if you add a description to one of the accounts, it is considered unique:
// 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
System.assertEquals(accountSet.size(), 2);

Uniqueness of objects of user-defined types is determined by the equals and hashCode methods, which you provide in your classes.

For more information, including a complete list of all supported set system methods, see Set Methods.

Note the following limitations on sets:
© Copyright 2000–2013 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.