1Z0-809 · Question #146
Given the code fragment: 13. list colors = new ArrayList<>(); 14. colors.add("green"); 15. colors.add("red"); 16. colors.add("blue"); 17. colors.add("yellow"); 18. colors.remove(2); 19…
The correct answer is D. [green, red, yellow, cyan]. There is an error in this question's stated answer - tracing the code reveals the output is actually A, not D. Here is the step-by-step trace: | Line | Operation | List state | |------|-----------|------------| | 14–17 | Four add() calls | [green, red, blue, yellow] | | 18 |…
Question
- list colors = new ArrayList<>();
- colors.add("green");
- colors.add("red");
- colors.add("blue");
- colors.add("yellow");
- colors.remove(2);
- colors.add(2, "cyan");
- System.out.print(colors);
Options
- A[green, red, cyan, yellow]
- BAn IndexOutOfBoundsException is thrown at runtime.
- C[green, blue, yellow, cyan]
- D[green, red, yellow, cyan]
How the community answered
(40 responses)- A8% (3)
- B5% (2)
- C15% (6)
- D73% (29)
Explanation
There is an error in this question's stated answer - tracing the code reveals the output is actually A, not D. Here is the step-by-step trace:
| Line | Operation | List state |
|---|---|---|
| 14–17 | Four add() calls | [green, red, blue, yellow] |
| 18 | remove(2) - removes element at index 2 ("blue") | [green, red, yellow] |
| 19 | add(2, "cyan") - inserts "cyan at index 2, shifting "yellow" right | [green, red, cyan, yellow] |
| 20 | System.out.print(colors) | prints [green, red, cyan, yellow] |
Why A is actually correct: ArrayList.remove(int index) removes by position (not by value), so remove(2) deletes "blue". Then add(2, "cyan") inserts at index 2, pushing "yellow" to index 3 - yielding [green, red, cyan, yellow].
Why the distractors fail:
- B - no exception is thrown; index 2 is valid at both lines 18 and 19.
- C - would require
remove(1)(removing "red"), notremove(2). - D - would be correct only if line 19 were
colors.add("cyan")(no index argument), which appends to the end.
Memory tip: With ArrayList, add(i, val) inserts (shifts right) and remove(i) deletes (shifts left) - both operate on a zero-based index. When an exam shows both on consecutive lines, redraw the list state after each call to avoid mixing them up.
Note for the exam taker: If this question appears on your actual exam with answer D marked correct, the answer key likely contains a typo on line 19 (it should read
colors.add("cyan")without an index). Raise it with your instructor.
Community Discussion
No community discussion yet for this question.