Experience Salesforce

Sets in APEX

What You’ll Learn

  • What Is Set In Apex?
  • Syntax Of Set In Apex
  • Characterstics Of Set In Apex

What is Set in Apex?

A Set in Apex is a collection of unique, unordered 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. A set can contain up to seven levels of nested collections inside it, that is, up to eight levels overall.

Syntax of Set in Apex

The basic syntax of creating a set is as follows:

Set<datatype> set1 = new Set<datatype>;  //ORSet<datatype> = new Set<datatype>{value1, value2,…}

Characteristics Of Set In Apex

The main characteristic of a set is the uniqueness of the elements. You can safely try to add the same element to a set more than once and it will disregard the duplicate without throwing an exception.

Set<String> collections = new Set<String>{‘Lists’, ’Sets’, ‘Maps’};

However, there is a slight twist with sObject i.e. the uniqueness of the data respects Case Sensitivity. The uniqueness of sObject is determined by comparing fields in their object.

Limitations of Sets in Apex

There are a few limitations of sets that you should be aware of:

  • Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a set in their declarations (for example, HashSet or TreeSet). Apex uses a hash structure for all sets.
  • A set is an unordered collection—you can’t access a set element at a specific index. You can only iterate over set elements.
  • The iteration order of set elements is deterministic, so you can rely on the order being the same in each subsequent execution of the same code.
Salesforce certifications
Next Topic

Need Extra Support? Our FREE study materials have got you covered.

Our expert-prepared study materials provide the answers you need. Clear your doubts and improve your skills with detailed notes from industry professionals.

cts-img
Rakshabandhan Sale