Exam 1z0-819 All QuestionsBrowse all questions from this exam
Question 124

Given the code fragment:

What is the result?

    Correct Answer: C

    The code defines a Comparator that sorts the elements in reverse order using b.compareTo(a). When the array 'towns' is sorted using this Comparator, the array order will be ['paris', 'oman', 'boston', 'bangkok']. The binary search operation, also using this Comparator, will then find 'oman' at index 1 in the sorted array. Therefore, the output will be 1.

Discussion
ASPushkinOption: C

---- reverse order : Comparator<String> ms = (a,b) -> b.compareTo(a); b.compareTo(a) -1 b < a 1 b > a Comparator int compare (T o1, T o2) -1 01<02 Arrays.sort(towns, ms); returns [paris, oman, boston, bankok] System.out.println(Arrays.binarySearch(towns,"oman",ms)); returns 1 because ms comparator sorting is the same as before (Arrays.sort(towns, ms))

d7bb0b2Option: C

sort by comparator, and then the same comparator indiques to binary search how element is ordered. so print 1=> paris, oman, boston, bangkok

StavokOption: C

Arrays.sort method is then called with the towns array and the ms comparator, sorting the array in reverse order. The resulting sorted array is ["paris", "oman", "boston", "bangkok"]. The Arrays.binarySearch method is then called with the sorted towns array, the search key "oman", and the ms comparator. Since "oman" is found at index 1 in the sorted array, the method returns 1.

Stavok

However, there is a compilation error in the code because the Comparator interface is generic and requires type arguments. The correct way to define the ms comparator would be: Comparator<String> ms = (a, b) -> b.compareTo(a); which will print 1 after compilation

Stavok

However, there is a compilation error in the code because the Comparator interface is generic and requires type arguments. The correct way to define the ms comparator would be:Comparator<String> ms = (a, b) -> b.compareTo(a); which will print 1 after compilation

KiraguJohnOption: C

C please not that Comparator<String> ms = (a,b)->b.compareTo(a) is not going to give you the same order as Comparator<String> ms = (a,b)->a.compareTo(b) one is descending and the other is ascending