3

Lists Initialization in APEX

Lists in Apex are dynamic arrays that can grow or shrink in size. They are used to store collections of elements, making them very useful for handling multiple values. Understanding how to initialize lists in Apex is fundamental for developers working on the Salesforce platform.

Syntax of List Initialization

The syntax for initializing a list in Apex involves specifying the type of the list and creating a new instance of it. Here is the basic syntax:

List<DataType> listName = new List<DataType>();

Example of List Initialization

Here is an example demonstrating how to initialize a list in Apex:

  1. Initializing a list of integers
List<Integer> integerList = new List<Integer>();
  1. Initializing a list of strings
List<String> stringList = new List<String>();
  1.  Initializing a list of custom objects
List<MyCustomObject> customObjectList = new List<MyCustomObject>();

How to Initialize List in Apex?

There are several ways to initialize a list in Apex:

Using the New Keyword

This is the most common method to initialize a list.

List<String> names = new List<String>();   names.add(‘John’);   names.add(‘Jane’);

Using List Literals

This method allows you to initialize and populate the list at the same time.

List<String> fruits = new List<String>{‘Apple’, ‘Banana’, ‘Cherry’};

Using Another List

You can initialize a list using another list.

List<String> originalList = new List<String>{‘One’, ‘Two’};List<String> newList = new List<String>(originalList);

Using the `addAll` Method

You can also use the `addAll` method to initialize a list with the values from another list.

List<String> firstList = new List<String>{‘Red’, ‘Blue’};List<String> secondList = new List<String>();secondList.addAll(firstList);




Salesforce Business Analyst Career Training
Next Topic

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

ServiceNow Stripe