1Z0-808 · Question #2
Given: public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Robb"); names.add("Bran"); names.add("Rick"); names.add("Bran"); if (names.remove("Bran")) {…
The correct answer is A. [Robb, Rick, Bran]. List.remove(String) removes only the first occurrence of the target and returns true if successful - so names.remove("Bran") removes the first "Bran" and the list becomes ["Robb", "Rick", "Bran"], then the if block executes names.remove("Jon"). Since "Jon" is not in the list…
Question
Options
- A[Robb, Rick, Bran]
- B[Robb, Rick]
- C[Robb, Bran, Rick, Bran]
- DAn exception is thrown at runtime.
How the community answered
(22 responses)- A82% (18)
- B9% (2)
- C5% (1)
- D5% (1)
Explanation
List.remove(String) removes only the first occurrence of the target and returns true if successful - so names.remove("Bran") removes the first "Bran" and the list becomes ["Robb", "Rick", "Bran"], then the if block executes names.remove("Jon"). Since "Jon" is not in the list, remove() simply returns false without throwing any exception, leaving the list unchanged at [Robb, Rick, Bran].
B is wrong because names.remove("Jon") does nothing - it doesn't remove the remaining "Bran". C is wrong because "Bran" is in the list, so the if condition is true and removal does occur. D is wrong because ArrayList.remove(Object) is designed to return false gracefully when the element isn't found - no exception is thrown.
Memory tip: Think of List.remove(Object) as a polite search-and-destroy - it finds the first match and removes it, or quietly gives up (returns false) if nothing is found; it never panics.
Topics
Community Discussion
No community discussion yet for this question.