Notes
Lists can contain sObjects among other types of elements. Lists of sObjects can be used for bulk processing of data.
To declare a list of sObjects, use the List keyword followed by the sObject type within <> characters.
Creating an empty list of Accounts:
List<Account> acList = new List<Account>();
Creating a list of all Accounts:
List<Account> acList = [SELECT Id, Name FROM Account];
Creating a list of 10 Accounts:
List<Account> acList = [SELECT Id, Name FROM Account LIMIT 10];
Adding and Retrieving List Elements
Define a new Contact List:
List<Contact> conList = new List<Contact>();
Create a Contact:
Contact con = new Contact(Lastname ='Scott')];
Add the contact to the list:
conList.add(con);
Retrieve the element at index 0:
conList.get(0);
Retrieve the Last Name of the Contact at index 0:
conList.get(0).lastname;
Bulk Processing
You can bulk-process a list of sObjects by passing a list to the DML operation.
Define an Account List:
List<Account> acList = new List<Account>();
Create three Accounts:
Account ac1 = new Account(Name='New Account 01');
Account ac2 = new Account(Name='New Account 02');
Account ac3 = new Account(Name='New Account 03');
Add all these three accounts to the list:
acList.add(ac1);
acList.add(ac2);
acList.add(ac3);
Bulk insert the list to the database:
insert acList;