Experience Salesforce

Lists Initialization in APEX

What You’ll Learn

  • Syntax of List Initialization
  • Example of List Initialization
  • How to Initialize List 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 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