Card 09/ 10
Practice: What Three Methods Do to the Caller's List
One follows the address, one overwrites its copy, one empties the list: predict what the caller holds.
A method that uses the reference it was passed changes the caller's object; one that assigns to its parameter changes nothing the caller can see. Each of the three methods below is called once on a fresh [start] list. Write down what the caller prints after each, all three before opening the answer.
static void one(List<String> xs) { xs.add("x"); }
static void two(List<String> xs) { xs = new ArrayList<>(); xs.add("y"); }
static void three(List<String> xs) { xs.clear(); xs.add("z"); }
List<String> a = new ArrayList<>(List.of("start"));
one(a);
System.out.println(a);What does the caller print after each of the three, starting from [start] each time?
| Method | Caller prints | Why |
|---|---|---|
one | [start, x] | Followed the address and changed the list |
two | [start] | Pointed its own variable elsewhere, then changed something the caller cannot reach |
three | [z] | Followed the address twice: emptied the caller's list, then added to it |
The test to apply to any method is one question: does it use the reference, or does it assign to the variable holding it? Using it reaches the caller's object. Assigning to it reaches nothing.
three is the one to look at closely. It is the most destructive of the three and the only one whose name gives no hint that it will empty what you handed it.
← → move through sections and cards