Lists, Sets, and Maps are the heart of Apex. But one wrong index or a missing key can bring your entire transaction to a halt.
The Crash ❌
List<Account> accs = [SELECT Id FROM Account LIMIT 0];
// Trying to access index 0 of an empty list
Id firstAcc = accs[0].Id;
The Pro Fix ✅
if(!accs.isEmpty()) {
Id firstAcc = accs[0].Id;
} else {
// Handle the empty state
}
The Crash ❌
Map<Id, Contact> conMap = new Map<Id, Contact>();
// someId does not exist in the map
String name = conMap.get(someId).Name;
The Pro Fix ✅
// Use the Safe Navigation Operator
String name = conMap.get(someId)?.Name;
// OR Check if it contains the key
if(conMap.containsKey(someId)) { ... }
The Crash ❌
for(Account a : accList) {
// Cannot remove items from the list we are currently looping!
accList.remove(a);
}
Pro Solution: Never remove items from a list while iterating over it. Instead, create a new list of "Items to Remove" and process them after the loop is finished.
Lists are ordered. The most common error is the ListIndexOutOfBoundsException, which happens when you ask
for a seat that doesn't exist.
Sets ensure uniqueness. They are unordered, meaning you can't use an index. The "trap" here is forgetting that Sets are Case-Sensitive for strings.
Maps are for bulkification. The danger zone is the NullPointerException when calling get() on a key that doesn't exist.