Sub topic 2
Lists: ordered and indexed
This chapter covers the Apex List: how to create one, read and change its elements, and what to watch for. It assumes you know basic Apex syntax (variables, primitive types, loops, conditionals), you have seen SObjects such as Account and Contact, and you can read a simple SOQL query.
What a List is
A List is an ordered collection of elements that all have the same type. Three properties define it:
- Ordered. Elements stay in the order you added them, unless you sort the list.
- Indexed. Each element has a position, starting at 0.
- Duplicates allowed. The same value can appear many times.
Choose a List when position matters or when repeated values are valid. If you only need unique values, a Set is a better fit. That is covered in a later chapter.
Creating a List
You can create an empty list or fill it with a literal.
List<String> empty = new List<String>();
List<String> names = new List<String>{'Ada', 'Grace'};The type goes inside the angle brackets. An Apex list can hold primitives, SObjects, custom classes, or other collections.
Reading and changing elements
Use add to append, or add(index, value) to insert at a position. Read elements with get or with bracket syntax. Both use zero-based indexes.
List<String> names = new List<String>{'Ada', 'Grace'};
names.add('Linus');
names.add(0, 'Alan');
System.debug(names.get(1)); // Ada
System.debug(names[2]); // Grace
names.sort();
System.debug(names); // (Ada, Alan, Grace, Linus)Walking through it:
- The list starts as
Ada, Grace. add('Linus')appends, givingAda, Grace, Linus.add(0, 'Alan')inserts at the front and shifts the others right, givingAlan, Ada, Grace, Linus.get(1)returnsAda, andnames[2]returnsGrace.sort()reorders the list in place, in ascending order.
Other common methods
| Method | What it does |
|---|---|
| `size()` | Returns the number of elements. |
| `isEmpty()` | Returns true when the list has no elements. |
| `set(index, value)` | Replaces the element at an index. |
| `remove(index)` | Removes the element at an index and returns it. |
| `contains(value)` | Returns true if the value is in the list. |
| `indexOf(value)` | Returns the first index of the value, or -1 if absent. |
| `clear()` | Removes all elements. |
List<Integer> scores = new List<Integer>{10, 20, 30};
scores.set(1, 25); // (10, 25, 30)
Integer removed = scores.remove(0); // 10
System.debug(scores); // (25, 30)
System.debug(scores.indexOf(30)); // 1Common errors
- Index out of range. Calling
get(5)on a three-element list throws aSystem.ListException. Checksize()first when the index is not guaranteed. - Negative or too-large index in
add(index, value). The same exception applies. - Wrong assumption about
sort().sort()changes the list and returns nothing. Writingnames = names.sort();does not compile. - Confusing
setwith the Set type.list.set(i, v)replaces by position. It has nothing to do with the Set collection.
Exercise
A list holds {'x', 'y', 'z'}. After list.add(1, 'w'); and list.remove(0);, what does the list contain, and what does list[1] return?
Show answer
After add(1, 'w') the list is x, w, y, z. After remove(0) it is w, y, z. So list[1] returns 'y'.
Exercise
What happens when you run List<Integer> nums = new List<Integer>{1, 2}; Integer n = nums.get(2);, and how can you avoid it?
Show answer
It throws a System.ListException, because valid indexes are 0 and 1. Avoid it by checking that the index is less than nums.size() before calling get.