1Z0-811 · Question #58
Given the code fragment: List<String> fls = new ArrayList<>(); fls.add("jasmine"); fls.add("rose"); fls.add("lotus"); fls.remove(2); fls.set(2, "lily"); System.out.println(fls); What is the result?
The correct answer is B. A runtime exception is thrown. After fls.remove(2) successfully removes "lotus" at index 2, the list contains only two elements - ["jasmine", "rose"] - with valid indices 0 and 1. The subsequent fls.set(2, "lily") attempts to assign to index 2, which no longer exists, causing an IndexOutOfBoundsException at…
Question
Options
- A[jasmine, rose, lily]
- BA runtime exception is thrown.
- C[jasmine, lily, lotus]
- D[jasmine, rose, lotus, lily]
How the community answered
(33 responses)- A12% (4)
- B76% (25)
- C6% (2)
- D6% (2)
Explanation
After fls.remove(2) successfully removes "lotus" at index 2, the list contains only two elements - ["jasmine", "rose"] - with valid indices 0 and 1. The subsequent fls.set(2, "lily") attempts to assign to index 2, which no longer exists, causing an IndexOutOfBoundsException at runtime.
Why the distractors fail:
- A assumes
set(2, "lily")succeeds, but the list only has indices 0–1 at that point. - C assumes the operations are reordered (set before remove) - the code runs top-to-bottom, so this is impossible.
- D confuses
set()(replaces an element) withadd()(appends one); even if the index were valid, it would replace, not append.
Memory tip: Think of remove(index) as "the list collapses" - indices above the removed position shift down and the list shrinks by one. Any index that was the last valid one before the remove becomes out-of-bounds immediately after.
Topics
Community Discussion
No community discussion yet for this question.