3

Lists Initialization in APEX

Lists in Apex are dynamic arrays that can grow or shrink. They are used to store collections of elements, making them very useful for handling multiple values. Lists in Apex are ordered and have index-based collections that let you create duplicate elements. These are Zero-indexed, which means the first element is at 0 index. 

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 listName = new List();

Example of List Initialization

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

  1. Initializing a list of integers
List integerList = new List();
  1. Initializing a list of strings
List stringList = new List();
  1.  Initializing a list of custom objects
List customObjectList = new List();

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 names = new List();   names.add('John');   names.add('Jane');

Using List Literals

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

List fruits = new List{'Apple', 'Banana', 'Cherry'};

Using Another List

You can initialize a list using another list.

List originalList = new List{'One', 'Two'};List newList = new List(originalList);

Using the `addAll` Method

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

List firstList = new List{'Red', 'Blue'};List secondList = new List();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.

Frequently Asked Questions

What is list initialization in Apex Salesforce?

List initialization in Apex Salesforce is a way to declare List variables and create instances using the ‘new’ keyword.

What is the difference between {} and () when initializing a list in Apex?

The {} curly brackets are used to initialize a list with values during declaration. The () parentheses are used to create an empty list or initialize a list from another list.

How do I initialize a list of sObjects in Apex?

    To initialize a list of sObjects in Apex, you can initialize the list of sObjects by:
  • From SOQL query:
  • List accounts = [SELECT Id, Name FROM Account LIMIT 10];
  • Manually:
  • List accounts = new List();
  • accounts.add(new Account(Name='Test Account'));

Can a list be null in Apex?

If a list is declared but not initialized, it can be null in Apex.

Book Free15-Minutes Career Counselling