Sub topic 3
Working with List methods
This chapter assumes you know basic Apex syntax and can declare a List with literal syntax. It covers the methods you will use most often to add, read, change, remove, and search elements.
Adding elements
add(element) appends to the end. add(index, element) inserts at a position and shifts later elements right. addAll appends every element of another list or set.
List<String> names = new List<String>{'Ada', 'Grace', 'Linus'};
names.add('Alan'); // Ada, Grace, Linus, Alan
names.add(1, 'Edsger'); // Ada, Edsger, Grace, Linus, Alan
names.addAll(new List<String>{'Barbara'});
System.debug(names.size()); // 6Reading and changing elements
get(index) and list[index] read an element. set(index, element) replaces one. Indexes start at 0, and an index outside the list throws a ListException.
names.set(0, 'Ada L.');
System.debug(names.get(0)); // Ada L.
System.debug(names[1]); // EdsgerRemoving elements
remove(index) deletes the element at that position and returns it. clear() empties the list. isEmpty() tests for no elements.
String removed = names.remove(2); // removes Grace
System.debug(removed); // Grace
System.debug(names.isEmpty()); // falseSearching and slicing
contains returns a Boolean. indexOf returns the first matching position, or -1 when there is no match. subList(start, end) returns a new list that includes start and excludes end.
System.debug(names.contains('Alan')); // true
System.debug(names.indexOf('Linus')); // 3
System.debug(names.indexOf('Zed')); // -1
List<String> middle = names.subList(1, 3);
System.debug(middle); // (Edsger, Linus)Sorting
sort() orders the list in place and returns nothing. Strings sort by character value, so uppercase letters come before lowercase ones.
names.sort();
System.debug(names);Quick reference
| Method | Returns | Notes |
|---|---|---|
| `add(e)` | nothing | Appends to the end |
| `add(i, e)` | nothing | Inserts, shifting later elements |
| `get(i)` | element | Throws `ListException` if out of bounds |
| `set(i, e)` | nothing | Replaces the element at `i` |
| `remove(i)` | removed element | Shifts later elements left |
| `indexOf(e)` | Integer | -1 when absent |
| `subList(s, e)` | List | End index is exclusive |
| `sort()` | nothing | Sorts in place |
Common errors
- Index out of bounds. Check
size()orisEmpty()before callingget(0)on a list that might be empty, such as a query result. - Using the return value of
sort().names = names.sort();does not compile, becausesort()returns nothing. - Removing while iterating. Do not call
removeon a list inside a for-each loop over that same list. Loop backward by index, or build a second list of the elements to keep. - Wrong
removeargument.removetakes an index, not a value. To delete by value, callindexOffirst and check that the result is not -1.
List<Integer> scores = new List<Integer>{5, 12, 7, 12};
for (Integer i = scores.size() - 1; i >= 0; i--) {
if (scores[i] == 12) {
scores.remove(i);
}
}
System.debug(scores); // (5, 7)Looping backward is safe because removing an element only shifts the elements after it, and those have already been visited.
Exercise
A list holds {'a', 'b', 'c', 'd'}. What does subList(1, 3) return, and what does indexOf('e') return?
Show answer
subList(1, 3) returns ('b', 'c'), because the end index is exclusive. indexOf('e') returns -1, because 'e' is not in the list.