7.2 The differences between List and Set

The concept

In our last post, we have introduced Set. However, you might wonder, why do we want to use Set since List seems more convenient? Actually, although the grammars of Set and List may look similar, their data structure underneath is very different.

A List is stored in a continuous physical space from computer’s perspective, as in the image below:

intarray

A set, however, doesn’t need to be stored in a continuous space. It has another internal logic to know which elements belong to one Set. So for a Set, it is impossible to tell the sequence of its elements. However, based on its implementation logic, it is easier for a Set to tell whether it¬†contains a specific value. It can easily distinguish duplicate values based on this.

Now let the code speaks:


List<Integer> intList = new List<Integer>{2,3,3,4,5};
Set<Integer> intSet = new Set<Integer>(intList);

System.debug('The set is: ' + intSet);

if(intSet.contains(4)) 
{
    System.debug('4 is inside the Set!');
}
else 
{
    System.debug('4 is not inside the Set!');
}

//There is no direct way to achieve the same thing in List
Boolean containsInList = false;
for(Integer curNum: intList)
{
    if(curNum == 6) //found
    {
        containsInList = true;
        break;
    }
}

if(containsInList)
{
    System.debug('6 is inside the List!');
}
else 
{
    System.debug('6 is not inside the List!');
} 

Your result should be similar to the screenshot below:
setandlist

A bit explanation

A set can be initialised via a list and vice versa. As shown in the above sample.

A set can use contains() to determine whether it contains a specific value but a list can’t.

Exercise

Try to add duplicate values into a list and debug the list, see how it looks like.

Next Post

7.3 Introducing Map

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *