Sub topic 3
Working with List methods
This chapter covers the methods you use most often on a List in Apex: adding, reading, replacing, removing, searching, slicing, and sorting. It assumes you can write basic Apex (variables, loops, conditionals) and that you know what a List is from the previous chapter. It does not use SOQL, so you can run every example in Anonymous Apex.
How List methods are grouped
Every method on a List does one of four jobs. It changes the list, reads from it, searches it, or creates a new list from it. Knowing which kind a method is tells you whether it can fail or surprise you.
Adding elements
add(element) appends to the end. add(index, element) inserts at a position and shifts later elements one place to the right. addAll(collection) appends every element of another list or set.
List<String> names = new List<String>{'Ada', 'Grace'};
names.add('Linus'); // (Ada, Grace, Linus)
names.add(0, 'Alan'); // (Alan, Ada, Grace, Linus)
names.addAll(new List<String>{'Edsger', 'Barbara'});
System.debug(names); // (Alan, Ada, Grace, Linus, Edsger, Barbara)
System.debug(names.size()); // 6The index in add(index, element) must be between 0 and the current size. Passing the size appends. Passing anything larger throws a System.ListException.
Reading and replacing elements
get(index) and the bracket form names[index] are equivalent. Indexes start at 0. set(index, element) replaces the element at that position and does not change the size.
names.set(1, 'Augusta'); // (Alan, Augusta, Grace, Linus, Edsger, Barbara)
System.debug(names.get(1)); // Augusta
System.debug(names[2]); // Grace
System.debug(names.isEmpty()); // falseset only works on an index that already exists. You cannot use it to grow a list. Use add for that.
Out-of-range access
Reading or setting an index that does not exist throws a System.ListException. An empty list has no valid index, so get(0) on an empty list also fails. Guard the access when the list might be short.
List<String> empty = new List<String>();
try {
System.debug(empty.get(0));
} catch (ListException e) {
System.debug(e.getMessage()); // List index out of bounds: 0
}
if (!empty.isEmpty()) {
System.debug(empty[0]);
}Prefer isEmpty() over size() == 0. It states the intent directly.
Removing elements
remove(index) deletes the element at that position, shifts the later elements left, and returns the removed element. clear() removes everything.
String removed = names.remove(0); // Alan
System.debug(removed);
System.debug(names); // (Augusta, Grace, Linus, Edsger, Barbara)
names.clear();
System.debug(names.size()); // 0List has no method that removes by value. To remove a known value, find its index first with indexOf, then call remove(index).
Do not remove inside a for-each loop
Changing the size of a list while a for (String n : names) loop is reading it throws a System.FinalException. To filter a list in place, loop over the indexes from the end to the start. Removing an element then never shifts an index you have yet to visit.
List<Integer> scores = new List<Integer>{40, 85, 12, 90, 55};
for (Integer i = scores.size() - 1; i >= 0; i--) {
if (scores[i] < 50) {
scores.remove(i);
}
}
System.debug(scores); // (85, 90, 55)A second approach is often clearer. Build a new list that holds only the elements you want to keep.
List<Integer> kept = new List<Integer>();
for (Integer s : new List<Integer>{40, 85, 12, 90, 55}) {
if (s >= 50) {
kept.add(s);
}
}
System.debug(kept); // (85, 90, 55)The backward loop avoids a second list. The rebuild approach leaves the original untouched. Pick based on whether you need the original afterward.
Searching
contains(element) returns a Boolean. indexOf(element) returns the index of the first match, or -1 when there is none. Both compare with equals, so they work on Strings, Integers, Ids, and objects that define equality.
List<String> team = new List<String>{'Ada', 'Grace', 'Linus', 'Grace'};
System.debug(team.contains('Linus')); // true
System.debug(team.indexOf('Grace')); // 1
System.debug(team.indexOf('Zed')); // -1Both methods scan the list from the start, so the cost grows with its length. Calling contains inside a loop over another large list multiplies the work. When you need many membership checks, copy the values into a Set once and use its contains. The Set chapter covers this.
Slicing and sorting
subList(startIndex, endIndex) returns a new list holding the elements from startIndex up to, but not including, endIndex.
sort() orders the list in place in ascending order and returns nothing. It does not return a sorted copy.
List<String> people = new List<String>{'Linus', 'Augusta', 'Grace', 'Edsger', 'Barbara'};
List<String> middle = people.subList(1, 3);
System.debug(middle); // (Augusta, Grace)
people.sort();
System.debug(people); // (Augusta, Barbara, Edsger, Grace, Linus)Copying a list
Assigning one list variable to another does not copy the list. Both variables point at the same list, so a change through one shows up in the other. clone() makes a new list with the same elements.
List<String> original = new List<String>{'a', 'b'};
List<String> alias = original;
List<String> copy = original.clone();
original.add('c');
System.debug(alias.size()); // 3, same list as original
System.debug(copy.size()); // 2, independent listFor a list of Strings or numbers, clone() gives you a fully independent copy. For a list of SObjects or other objects, the new list holds the same object references, so editing a record through one list also changes it in the other. deepClone() exists for lists of SObjects to copy the records as well. The reference chapter covers both in detail.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Calling `get(i)` on an empty or short list | `System.ListException` | Check `isEmpty()` or `size()` first |
| Using `set(i, x)` to add an element | `System.ListException` | Use `add` |
| Removing inside a for-each loop | `System.FinalException` | Loop backward by index, or build a new list |
| Writing `sorted = names.sort()` | Compile error, because `sort()` returns nothing | Call `names.sort()` and use `names` |
| Assigning a list to another variable and expecting a copy | Both variables change together | Use `clone()` |
| Calling `contains` on a large list inside a loop | Slow code that can hit CPU limits | Build a `Set` once |
Exercise
A list List<String> items = new List<String>{'x', 'y', 'z'}; is given. Write the statements that insert 'w' at the front, replace 'y' with 'Y', and remove the last element. What does the list hold at the end?
Show answer
items.add(0, 'w'); gives (w, x, y, z). items.set(2, 'Y'); gives (w, x, Y, z), because 'y' moved to index 2 after the insert. items.remove(items.size() - 1); gives (w, x, Y). The final list is (w, x, Y).
Exercise
This code is meant to delete every empty String from a list, but it throws an exception. Explain why and rewrite it. List<String> parts = new List<String>{'a', '', 'b', ''}; for (String p : parts) { if (p == '') { parts.remove(parts.indexOf(p)); } }
Show answer
The for-each loop is iterating over parts, and remove changes its size during the iteration, which throws a System.FinalException. Loop backward by index instead: for (Integer i = parts.size() - 1; i >= 0; i--) { if (parts[i] == '') { parts.remove(i); } }. The list ends as (a, b). Building a new list that adds only the non-empty values also works.