List - Index
Not Started

The elements of a List are not helpful until we can access them.

Recall that variables point to a location in memory. When a List is initialized, memory addresses are allocated adjacently for each element. This makes the List collection very efficient at accessing elements because they're all stored sequentially. These consecutive memory locations are referred to as an index or indices.

Lists are ordered in Apex. The elements will always be arranged in the order they were inserted. We can take advantage of this by using square brackets [ ] to access an element by it's index:

List<String> names = new List<String>{'Jerry', 'George'}; String firstNameInList = names[0]; // firstNameInList is now Jerry String secondNameInList = names[1]; // secondNameInList is now George

The index starts at zero. Why? Well, recall that this data is stored sequentially. secondNameInList is a pointer and the index is an offset. The first element is at the pointer's memory location so its offset is zero. The second memory location is one slot further, hence the 1.

If the index starts at 0, the index matches the offset. Here's a visual representation of the List:

IndexElement
0Jerry
1George



Instead of using the square bracket [] notation, we can also use the List instance method - get(Integer):

List<String> names = new List<String>{'Jerry', 'George'}; String firstNameInList = names.get(0); // firstNameInList is now Jerry String secondNameInList = names.get(1); // secondNameInList is now George

There's no advantage to using one over the other, so use whichever notation you prefer.

Sometimes you'll want to find the index of an element. When you do, you'd use the indexOf(element) method:

List<String> names = new List<String>{'Jerry', 'George'}; Integer jerryIndex = names.indexOf('Jerry'); // returns 0 Integer georgeIndex = names.indexOf('George'); // returns 1 Integer elaineIndex = names.indexOf('Elaine'); // returns -1, because this value is not in the list

Lists do allow duplicate elements. Using indexOf(element) will return the first index the element is found in:

List<String> websiteName = new List<String>{'CampApex.org', 'CampApex.org', 'CampApex.org'}; Integer indexOfCampApex = websiteName.indexOf('CampApex.org'); // returns 0

Challenge

You've been provided a list of singers represented by Strings. Create a variable called secondSinger and set it to the second singer in the list. Use either the .get() method or the square brackets [].

Then, create another variable named indexOfBeyonce to store the index of Beyonce using the indexOf() method.