Collections.binarySearch() in Java

后端 未结 4 2138
攒了一身酷
攒了一身酷 2020-12-19 13:45

I\'m using the binarySearch() method to find the position of an element in the list. And I don\'t understand why the index is -6. I see that the element is at the position 1

4条回答
  •  猫巷女王i
    2020-12-19 14:25

    You must either sort in ascending order (per the documentation of Collections.binarySearch), or pass the custom comparator as the third parameter.

    int index = Collections.binarySearch(al, 50, Collections.reverseOrder());
    

    Failure to do this will cause undefined results.

提交回复
热议问题