When elements are added to a list, we say the size of a list is increased. The size of a list represents how many elements are in a list.
We can use the size()
instance method to determine this:
List<String> emailList = new List<String>(); Integer emailListSize = emailList.size(); // Returns 0 // There are 0 element in the list, so the size is 0 emailList.add('jerry@CampApex.com'); emailListSize = emailList.size(); // Returns 1 // There's 1 element in the list, so the size is 1 emailList.add('elaine@CampApex.com'); emailListSize = emailList.size(); // Returns 2 // There's 2 elements in the list, so the size is 2
This will come in handy in the next course when we loop through the elements of our list.
There are two ways to know if our List is empty. The first you already saw, if the size of a list is 0 then it's empty. A second way to check if using the isEmpty()
instance method. This method returns true if a list is empty, and returns false if elements are present.
List<String> emailList = new List<String>(); Integer emailListSize = emailList.size(); // Returns 0 Boolean isListEmpty = emailList.isEmpty(); // returns true
An empty list is not the same as a null list. As a refresher, this is the difference between null and empty using Strings:
String firstName; // firstName is Null - because it's never been initialized String middleName = ''; // middleName is empty, it's been initialized but not assigned a value String lastName = 'smith'; // lastName is both initialized and assigned a value firstName.capitalize(); // throws a null pointer exception because firstName is null middleName.capitalize(); // no exception, but there's nothing to capitalize lastName.capitalize(); // capitalizes smith into Smith
The same concept applies to Lists:
List<String> firstNamesList; // declared, but not in initialized List<String> middleNamesList = new List<String>(); // initialized, but not assigned elements List<String> lastNamesList = new List<String>{'Smith'}; // initialized and assigned elements firstNamesList.size(); // throws a null pointer exception middleNamesList.size(); // no exception. the list is empty, so returns 0 lastNamesList.size(); // list has been initialized and assigned elements, returns 1
We can check if a List is null like this:
List<String> firstNamesList; List<String> middleNamesList = new List<String>(); List<String> lastNamesList = new List<String>{'Smith'}; Boolean isFirstNameNull = firstNamesList == null; //returns TRUE Boolean isMiddleNameNull = middleNamesList == null; //returns FALSE Boolean isLastNameNull = lastNamesList == null; //returns FALSE