Sub topic 2
Lists: ordered and indexed
This chapter assumes you know basic Apex syntax (variables, primitive types, loops, conditionals) and have used SObjects and simple SOQL queries. It covers what a List is, how to create one, how indexing works, and the errors you will hit first. The next chapter covers the full method set.
What a List is
A List is an ordered collection of elements that all have the same type. It has three properties:
- Ordered. Elements stay in the order you added them, unless you sort or rearrange them.
- Indexed. Each element has a zero-based position, so the first element is at index 0 and the last is at
size() - 1. - Duplicates allowed. The same value can appear any number of times, including
null.
These properties separate a List from a Set, which has no duplicates and no positions, and from a Map, which looks values up by key. Choose a List when order matters, when you need to reach an element by position, or when repeated values are meaningful.
Creating Lists
Apex offers several ways to create a List. All of them produce the same kind of object.
List<String> empty = new List<String>();
List<Integer> primes = new List<Integer>{2, 3, 5, 7};
String[] colors = new String[]{'red', 'green'};
List<String> fromSet = new List<String>(new Set<String>{'x', 'y'});
System.debug(empty.size()); // 0
System.debug(primes); // (2, 3, 5, 7)
System.debug(colors); // (red, green)
System.debug(fromSet.size()); // 2new List<T>()creates an empty List.new List<T>{ ... }creates a List with initial values. This is the literal syntax.T[]is array notation.String[]andList<String>are the same type, and you can use either one wherever the other is expected. Apex has no separate fixed-size array type.- Passing a Set (or another List) to the constructor copies its elements. A Set has no defined order, so do not rely on the order of
fromSet.
The type in angle brackets is fixed at compile time. A List<Integer> cannot hold a String. The element type can be a primitive, an SObject, a custom class, or another collection.
Reading and writing by index
You read an element with get(index) or with bracket syntax. You replace an element with set(index, value) or by assigning to a bracket expression.
List<String> names = new List<String>{'Ada', 'Grace', 'Linus'};
String first = names.get(0); // Ada
String second = names[1]; // Grace
names.set(2, 'Barbara'); // replaces Linus
names[0] = 'Alan'; // replaces Ada
System.debug(names); // (Alan, Grace, Barbara)
System.debug(names.size()); // 3Replacing an element does not change the size. add(value) appends to the end and grows the List by one. add(index, value) inserts at a position and shifts later elements one place to the right.
List<String> letters = new List<String>{'a', 'c'};
letters.add('d'); // (a, c, d)
letters.add(1, 'b'); // (a, b, c, d)
System.debug(letters);
System.debug(letters.size()); // 4Out-of-bounds access
The most common List error is using an index that does not exist. The valid indexes for reading and replacing are 0 through size() - 1. Anything else throws a System.ListException, such as List index out of bounds: 3.
List<String> names = new List<String>{'Ada', 'Grace', 'Linus'};
try {
String missing = names.get(3);
} catch (ListException e) {
System.debug(e.getMessage()); // List index out of bounds: 3
}
try {
names.set(5, 'Edsger'); // set cannot extend the list
} catch (ListException e) {
System.debug(e.getMessage());
}Two points trip people up:
setnever grows a List. To add an element, useadd.- An empty List has no valid index at all, so
get(0)on an empty List also throws.
Production code rarely wraps these calls in try/catch. Check the size first:
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 1];
if (!accounts.isEmpty()) {
System.debug(accounts[0].Name);
} else {
System.debug('No accounts found');
}This check matters for SOQL. A query that matches no rows returns an empty List. It does not return null, so accounts[0] throws instead of giving you a null record.
Duplicates, nulls, and order
A List stores exactly what you add. It does not remove repeated values or reject null.
List<String> items = new List<String>{'a', null, 'a'};
items.add('b');
items.add('b');
System.debug(items); // (a, null, a, b, b)
System.debug(items.size()); // 5Because a List can contain null elements, a null result from get is ambiguous. It might mean the element is null, and that is different from the index being out of range, which throws. Conversely, a List variable that was never initialized is itself null, and calling a method on it throws a NullPointerException.
List<String> notReady; // null, no List exists yet
System.debug(notReady == null); // true
List<String> ready = new List<String>(); // a real, empty List
System.debug(ready.isEmpty()); // trueAlways initialize a List before you add to it.
Looping over a List
Two loop styles cover most work. The for-each loop is simpler and is the default choice. Use an index loop when you need the position or need to change elements in place.
List<Integer> scores = new List<Integer>{70, 85, 90};
// for-each: no index available
Integer total = 0;
for (Integer s : scores) {
total += s;
}
System.debug(total); // 245
// index loop: position is available, so elements can be replaced
for (Integer i = 0; i < scores.size(); i++) {
scores[i] = scores[i] + 5;
}
System.debug(scores); // (75, 90, 95)Do not add or remove elements from a List while a for-each loop is reading it. Apex can throw an exception when a collection changes during iteration. If you must remove elements in an index loop, walk backwards so removals do not shift the indexes you have yet to visit. Iteration over all three collection types is covered in a later chapter.
Lists of Lists and Lists of records
The element type can itself be a List, which gives you a table-like structure. Each inner List is a separate object and can have a different length.
List<List<Integer>> grid = new List<List<Integer>>();
grid.add(new List<Integer>{1, 2, 3});
grid.add(new List<Integer>{4, 5});
System.debug(grid[0][2]); // 3
System.debug(grid[1].size()); // 2Lists of SObjects appear constantly in Apex because SOQL queries return them, and DML statements accept them. Later chapters cover that in detail.
Assignment shares the same List
A List variable holds a reference to the List, not the List itself. Assigning one variable to another does not copy the elements.
List<String> a = new List<String>{'x'};
List<String> b = a; // b points to the same List as a
b.add('y');
System.debug(a); // (x, y)Copying with clone and deepClone is covered in the reference semantics chapter. For now, remember that passing a List to a method lets that method change your List.
Summary of when to choose a List
| Need | List fits? |
|---|---|
| Keep insertion order | Yes |
| Reach an element by position | Yes |
| Allow repeated values | Yes |
| Reject duplicates automatically | No, use a Set |
| Find a value by a key such as an Id | No, use a Map |
Exercise
A SOQL query returns no rows and you store the result in List<Contact> found. What does found[0] do, and how do you make the code safe?
Show answer
It throws a System.ListException (List index out of bounds: 0), because the query returns an empty List, not null and not a null record. Guard the access with if (!found.isEmpty()) { ... } or check found.size() > 0 before reading index 0.
Exercise
What do System.debug(items) and System.debug(items.size()) print for this code?
List<String> items = new List<String>{'a', 'b'};
items.add(0, 'c');
items.set(1, 'd');
items.add('d');
Show answer
The List is (c, d, b, d) and the size is 4. add(0, 'c') gives (c, a, b). set(1, 'd') replaces a, giving (c, d, b). The final add('d') appends a duplicate, giving (c, d, b, d).