1Z0-811 · Question #17
Given the code fragment: List<String> names = new ArrayList<>(); names.add("Julia"); names.add("Peter"); for (Iterator<String> itr = names.iterator(); itr.hasNext();) {…
The correct answer is C. Julia Peter. Option C is correct because ArrayList preserves insertion order, so the iterator visits "Julia" (added first) then "Peter" (added second), printing them on separate lines exactly as inserted. Option A is wrong because the code is syntactically valid Java - Iterator<String> with…
Question
Options
- AA compilation error occurs.
- BA runtime exception is thrown.
- CJulia Peter
- DPeter Julia
How the community answered
(40 responses)- A8% (3)
- B3% (1)
- C88% (35)
- D3% (1)
Explanation
Option C is correct because ArrayList preserves insertion order, so the iterator visits "Julia" (added first) then "Peter" (added second), printing them on separate lines exactly as inserted. Option A is wrong because the code is syntactically valid Java - Iterator<String> with hasNext() and next() is the standard, compiler-approved pattern. Option B is wrong because no exception is triggered: the list is not modified during iteration (which would cause a ConcurrentModificationException), and next() is never called past the end of the list. Option D is wrong because it implies reverse order, which would only occur with a stack-like structure (e.g., Deque) or explicit reversal - ArrayList's iterator always goes index 0 → N.
Memory tip: Think of ArrayList as a numbered line - whoever joins first gets spot #0, and the iterator always starts from the front of the line.
Topics
Community Discussion
No community discussion yet for this question.