Collections.binarySearch() in Java

后端 未结 4 2131
攒了一身酷
攒了一身酷 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条回答
  •  粉色の甜心
    2020-12-19 14:28

    Apart from the need for the list being sorted, binary Search

    returns the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1)

    (Javadoc)

    Ie: a negative index designates the negative of the index at which the item being searched would be placed if it were present, minus 1.

    I.e.

    -1 means it would be placed at index 0

    -6 means it would be placed at index 5.

提交回复
热议问题