You got a preview of List in the last lesson, but let's take our time and really understand them.
Before we look at Apex, think about a list in real life. A list represents a collection of elements, this could be a shopping list, a to-do list, a checklist, a list of your friends' phone numbers, or a list of all your neighbor's names.
In Apex, a List is a class that groups data from the same datatype together. Say you want to keep track of all your friends' names in Apex - Astro, Codey, Ruth, and Flo. Instead of creating a String variable for each, you can create a List of Strings to group all of them:
List<String> friends = new List<String> {'Astro', 'Codey', 'Ruth', 'Flo'};
You should recognize some of this syntax. You already know that new
creates an instance of a type, you know what a String
is, and you know the =
operator initializes and assigns variables.
The List<String>
syntax is new but straightforward. The datatype between the angle brackets <>
defines the datatype of the elements in the List.
The elements in the curly braces {}
initialize our List. The datatype here must match the datatype within the angle brackets <>
. You can pass in literals or variables.
Bringing it together, we're declaring a List of Strings named friends
and initializing it to a List of friends represented by String literals.
Lists can be of any datatype, here are some examples:
List<Integer> importantNumbers = new List<Integer> {1, 5, -2, 25, 0}; List<Decimal> importantDecimals = new List<Decimal> {0.01, 5.50, -2.20, 2.50, 0};