This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Simran Dass wrote:
I think the answer should be -5 through 4.
Please do a search first... as this question comes up often.
But to answer your questions.... here is an excerpt from the JavaDoc:
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.
Basically, when a match occurs, you will get an index of the match. In this case, it is 5 items with an index of zero to four. If there isn't a match, then you get an insertion point. The insertion point is defined as the first index that is greater than the searched value. Also, if nothing is greater, then you will get a value that is the size of the array. In this case, the possible insertion points would be zero to five (one for each index, and the size if it is greater than everything).
Of course, it is not possible to determine whether the result is an index or insertion point, if it just returns it. So, it doesn't something silly. If it is an insertion point then it negates and subtracts one more. This causes the result to be negative and guaranteed to be not zero.
Anyway, take zero, negate and subtract one, and you get negative one. Take five, negate and subtract one, and you get negative six. This gives the possible range for an insertion point return to be negative one to negative six. And an overall response of negative six to four.
But , its given that the array has five elements ( i.e. the indexes are 0,1,2,3,4 )
So the last positon where you can insert is at index 4. So should not the insertion point
be -4-1 = -5 . So where does -6 come from ??