5.1 A quick introduction to List in Apex

Before we proceed to learn loop, let’s first take some time to have a basic understanding of arrays in Apex.

By using variables, we can store data in programs. But often, we could need a list of information, instead of single pieces. For example, the names of all the students in one class; all the numbers from 1 to 1000; all the magic spell Harry Potter can play; all the pokermons you want to collect. In order to store that kind of data, we need to introduce List in Apex.

Below is the sample code in anonymous block:

List<String> seasons = new List<String>{'Winter', 'Spring', 'Summer'};
System.debug('First season is: ' + seasons[0]);
System.debug('Second season is: ' + seasons[1]);
System.debug('Third season is: ' + seasons[2]);

System.debug('Fourth season is: ' + seasons[3]);

Your result should be similar to below:


A bit explanation

List can be considered as a generalised object in Apex. The grammar is List<T> list_name. T here is the element type in the list. In Apex, one list can only contain one type of elements. In our example, the type is String.

If we want to put some initial elements into List, we can use the grammar shown in our code example. Otherwise, we can simply use List<String> seasons = new List<String>(); to define an empty list.

List is sequenced. That means the sequence of elements is fixed in the list. It means, if you put ‘Winter’s as the first element, it will always be in the first place.

Just like almost every other programming language, array’s index starts with 0. And ends with array’s length – 1. You can reference an array’s member by using list_name[index]. But make sure the index is within the range of the array. Otherwise, you will get an index out of bound exception.


Create a list of numbers from 1 to 10. Reference them. And try to obtains list_name[100] and see what error you have got.

Next post

5.2 Using for loop

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 *