开发者

Java Vector: How to find out the would-be index of an item

I would like to do the following in Java: I have an element, and I would like to know what would be its in开发者_如何学编程dex had it been inserted into a collection of other objects (given they're already sorted).

So if I have a vector of ints like this: 1,3,5,7,9 and I had the int '2' in hand, I'd know that its 'would-be' index is i=1, between values 1 and 3.


// assumes vector is sorted
// and that vector does not yet contain searchedObject
insertionPoint = -1 * Collections.binarySearch(vector,searchedObject) - 1;

Definition of Collections.binarySearch() states

Returns:

index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size(), if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜