Sub topic 9
Where a Variable Is Visible, and Lists, Sets, and Maps
This chapter assumes you can declare variables and write if and for statements in Apex. It covers where a variable can be used, and then the three collection types.
Where a variable is visible
A variable's scope is the part of the code where you can use it. In Apex, a variable exists from its declaration to the closing brace of the block that contains it. A block is any code between { and }, such as an if body or a loop body.
Apex does not allow a nested block to declare a variable with the same name as one in an enclosing block. This differs from some languages, where the inner variable shadows the outer one.
Integer total = 0;
for (Integer i = 0; i < 3; i++) {
Integer square = i * i;
total += square;
}
System.debug(total);
// System.debug(square); // Compile error: square is out of scope
// System.debug(i); // Compile error: i exists only inside the loopTwo common errors follow from these rules:
- Using a variable after its block has ended. Declare it before the block if you need it afterward.
- Redeclaring a name inside a nested block, such as declaring
Integer totalinside the loop above. Apex reports a duplicate variable error.
Two sibling blocks can each declare a variable with the same name, because neither block contains the other.
Lists, sets, and maps
Collections hold groups of values. Each one is declared with the type of its contents in angle brackets.
| Collection | Ordered | Duplicates | Access by |
|---|---|---|---|
| `List<T>` | Yes | Allowed | Zero-based index |
| `Set<T>` | No guaranteed order | Not allowed | Membership check |
| `Map<K, V>` | No guaranteed order | Keys unique, values may repeat | Key |
List<Integer> numbers = new List<Integer>{ 1, 2, 3 };
numbers.add(2);
System.debug(numbers.size());
System.debug(numbers[0]);
Set<String> tags = new Set<String>{ 'a', 'b' };
tags.add('a');
System.debug(tags.size());
System.debug(tags.contains('b'));
Map<String, Integer> stock = new Map<String, Integer>{ 'pens' => 10 };
stock.put('paper', 4);
System.debug(stock.get('pens'));
System.debug(stock.get('missing'));
System.debug(stock.containsKey('missing'));The list now holds four items, because lists keep duplicates. The set still holds two, because adding 'a' again changes nothing. stock.get('missing') returns null instead of throwing an error, so use containsKey when you need to tell a missing key from a stored null.
Reading a list index that does not exist throws a ListException. Check size() first when the index might be out of range.
Sets compare strings with case sensitivity, so 'a' and 'A' are two different members.
Exercise
A variable Integer count is declared inside a for loop body. You write System.debug(count); on the line after the loop's closing brace. What happens, and how do you fix it?
Show answer
The code fails to compile because count is out of scope after the loop's block ends. Declare Integer count before the loop and assign to it inside the loop.
Exercise
Given Map<String, Integer> stock = new Map<String, Integer>{ 'pens' => 10 };, what does stock.get('cups') return, and how can you check whether the key exists first?
Show answer
It returns null. Call stock.containsKey('cups') to test whether the key is present.