nerdexam
Oracle

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…

Working with Selected Classes from the Java API

Question

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")) { names.remove("Jon"); } System.out.println(names); } What is the result?

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)
  • A
    82% (18)
  • B
    9% (2)
  • C
    5% (1)
  • D
    5% (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

#ArrayList.remove()#Method return values#List operations#Control flow

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice