Newer Version Available
Lists of sObjects
You can use a list to store sObjects. Lists are useful when working with SOQL queries. SOQL queries return sObject data and this data can be stored in a list of sObjects. Also, you can use lists to perform bulk operations, such as inserting a list of sObjects with one call.
To declare a list of sObjects, use the List keyword followed by the sObject type within <> characters. For example:
Auto-populating a List from a SOQL Query
You can assign a List variable directly to the results of a SOQL query. The SOQL query returns a new list populated with the records returned. Make sure that the declared List variable contains the same sObject that is being queried. Or you can use the generic sObject data type.
This example shows how to declare and assign a list of accounts to the return value of a SOQL query. The query returns up to 1,000 returns account records containing the Id and Name fields.
Adding and Retrieving List Elements
As with lists of primitive data types, you can access and set elements of sObject lists using the List methods provided by Apex. For example:
Bulk Processing
Record ID Generation
Apex automatically generates IDs for each object in an sObject list that was inserted or upserted using DML. Therefore, a list that contains more than one instance of an sObject cannot be inserted or upserted even if it has a null ID. This situation would imply that two IDs would need to be written to the same structure in memory, which is illegal.
For example, the insert statement in the following block of code generates a ListException because it tries to insert a list with two references to the same sObject (a):
Using Array Notation for One-Dimensional Lists of sObjects
Alternatively, you can use the array notation (square brackets) to declare and reference lists of sObjects.
These examples also use the array notation with sObject lists.
| Example | Description |
|---|---|
|
|
Defines an Account list with no elements. |
|
|
Defines an Account list with memory allocated for three Accounts: a new Account object in the first position, null in the second, and another new Account object in the third. |
|
|
Defines the Contact list with a new list. |