This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes range of a Arrays.binarySearch() method? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "range of a Arrays.binarySearch() method?" Watch "range of a Arrays.binarySearch() method?" New topic

range of a Arrays.binarySearch() method?

Tanakorn Numrubporn
Ranch Hand

Joined: Dec 11, 2006
Posts: 81
Again, This question is derive for K&B Book from Chapter7: Generics and Collections in the Self Test section:
9.Given a properly prepared String array containing five elements, which range of results could a proper invocation of Arrays.binarySearch() produce?
E. -5 through 4
F. -5 through 5
G. -6 through 4
The answer is G.
Why not answers E. Because the insertion point is -(Insertion point) -1. This string array has five elements so max index is 4 and the min insertion point should be -4 -1 = -5. I don't understand, why this array min insertion point is -6
Priya Viswam
Ranch Hand

Joined: Dec 28, 2006
Posts: 81
Negative value indicates unsuccessful search and [-(Insertion point) -1 ]specifies where to insert the element.

The array already contains elements in positions 0,1,2,3 and 4. So we can insert elements from 5 onwards. So the answer should be G itself since
-(-6)-1 = 5.

SCJP 1.5<br />SCWCD 1.4
Tanakorn Numrubporn
Ranch Hand

Joined: Dec 11, 2006
Posts: 81
Thank you very much
Sanjeev Singh
Ranch Hand

Joined: Nov 01, 2006
Posts: 381
If the max search index is 4 that means there are 5 object in the collection.Lets name then A-E for then the insertion points will be 6(5 before each elements and 1 at the end).
search index:
[0 1 2 3 4 ]
| A | B | C | D | E
insertion points
[-1 -2 -3 -4 -5 -6(end)]
[ January 09, 2007: Message edited by: Sanjeev Kumar Singh ]

~Sanjeev Singh<br />SCJP 1.5
Tanakorn Numrubporn
Ranch Hand

Joined: Dec 11, 2006
Posts: 81
Thank you again for knowledgh that I gain.
But which of the two above replies is correct assume about the insertion point; between the first position that we can insert in array OR the space between adjacency elements of the array.
I agree. Here's the link:
subject: range of a Arrays.binarySearch() method?
It's not a secret anymore!