Last Updated : 10 Apr, 2024
ArrayList <Integer> list = new ArrayList<>();
list.add(3);
list.add(5);
list.add(2);
list.add(1);
list.add(6);
System.out.print(Collections.binarySearch(list, 2) + \" \");
Collections.sort(list);
System.out.print(Collections.binarySearch(list, 2)); 

Predict the correct output for the above code snippet
(A) 1 1
(B) 1 2
(C) undefined behavior 1
(D) 2 2


Answer: (C)

Explanation:
Collections.binarySearch(): position of an object in a sorted list.
At first the list is unsorted so it will result in undefined behavior.
After the sorting the list index of 2 becomes 1.


Share your thoughts in the comments