Lists Initialization in APEX
Chapter 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 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.