1Z0-829 · Question #13
Given the code fragment: List lst = new ArrayList<>(); lst.add("e1"); lst.add("e3"); lst.add("e2"); int x1 = Collections.binarySearch(lst, "e3"); System.out.println(x1); Collections.sort(lst); int…
The correct answer is B. 2. Option B (2) is correct because it represents x2 - the only binary search call that follows the required precondition: the list must be sorted first. After Collections.sort(lst), the list becomes ["e1", "e2", "e3"], and a binary search for "e3" correctly returns index 2…
Question
Options
- A0
- B2
- C-2
- D1
- E-1
How the community answered
(63 responses)- A5% (3)
- B68% (43)
- C10% (6)
- D2% (1)
- E16% (10)
Explanation
Option B (2) is correct because it represents x2 - the only binary search call that follows the required precondition: the list must be sorted first. After Collections.sort(lst), the list becomes ["e1", "e2", "e3"], and a binary search for "e3" correctly returns index 2 (zero-based).
The other options map to common misconceptions:
- D (1) tempts students who think x1 is valid - but binary search on the unsorted list
["e1", "e3", "e2"]violates the method's contract, making x1's result undefined (it may accidentally return 1, but this is not guaranteed behavior). - E (-1), C (-2) tempt students who expect x3 to return a "not found near index 0 or 1" result - but since
Collections.reverse()produces a descending-order list, the contract is violated again and the actual return value is unpredictable/implementation-defined. - A (0) has no strong basis in the logic but could trap students who miscount the sorted index.
Memory tip: Think "Sort Before Search" - Collections.binarySearch() requires a sorted list and returns the zero-based index on success, or a negative insertion-point value on failure. Any search on an unsorted or reverse-sorted list is undefined behavior and should be treated as wrong on exams.
Topics
Community Discussion
No community discussion yet for this question.