Experience Salesforce
Lists Initialization in APEX
What You’ll Learn
- Syntax of List Initialization
- Example of List Initialization
- How to Initialize List in Apex?
Topics
- Apex Data Types
- Integer Data Type in APEX
- Floating Point Data Type in APEX
- String Data Type in APEX
- Date Datatypes in APEX
- Time and DateTime Data Types in APEX
- Boolean Datatype in Salesforce
- ID & Blob Datatypes in APEX
- What is the Rule of Conversions in Apex?
- Enums in APEX
- sObjects in Salesforce
- Generic sObjects in Salesforce
- Collections in APEX
- Lists in APEX
- List Array Notation in APEX
- Lists Initialization in APEX
- Nested Lists in APEX
- Sets in APEX
- Sets Initialization And Methods
- Maps in APEX
- Map Initialization Methods in APEX
- Operators in Apex and Their Types
- Shorthand Operator
- Equality Operator
- Relational Operators(<,>,<=,>=)
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:
- Initializing a list of integers
List<Integer> integerList = new List<Integer>(); |
- Initializing a list of strings
List<String> stringList = new List<String>(); |
- 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); |
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.