File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collections.binarySearch(...) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collections.binarySearch(...)" Watch "Collections.binarySearch(...)" New topic


Deepak Chopra
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

I found the following conflicting problem:
according to k & B :
"if a collection/array you want to search was sorted using a Comparator,it must be searched using the same Comparator, which is passed as the second argument..."

Now I wrote a program:

Even though second time while searching I am passing only List and Object need to search..!! I was expecting some unexpecting behavior..!!
But I was shocked It gave me right answer ?

Can some one explain binary search behave behind the codes!!

DVDInfo has two parameter : name and size..!!!

Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
Alex Belisle Turcot
Ranch Hand

Joined: Apr 26, 2005
Posts: 516

I read the API, and here's my opinion.

Using a distinct Comparator is similar to using an unsorted list. For that new comparator, the data is not correctly sorted.

In the API, for binarySearch, it says:
If it is not sorted, the results are undefined. If the list contains multiple elements equal to the specified object, there is no guarantee which one will be found.

The binarySearch compares the elements and relies on the order for its correctness. You'll just end up not finding the object your are looking for.

[ January 23, 2008: Message edited by: Alex Belisle Turcot ]
Dean Jones
Ranch Hand

Joined: Dec 29, 2007
Posts: 129
Dear Sunny, can you please provide the full code, to make it clear.
Deepak Chopra
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

Hi, There was some problem in my code I have corrected that, But still I have some confusion, Please help me to clear that :

1) I have created one list containing movie Object

Movie Object has two properties : Name and Size

2) I sorted out the list according to Movie name

3) I sorted out again on the base of size

4) There are some movies with equal size

5) Now I searched out one movie with unique name and non unique Size

6) First I did not pass the Comparator Object

7) result is correct position.

8) Now I pass the comparator Object, result is unexpected, Some strange positive integer.

9) Now I try to search a movie with unique size

10) first search without Comparator, Result is some negative integer as expected

11) Now I pass comparator Object, result is correct position.
I agree. Here's the link:
subject: Collections.binarySearch(...)
jQuery in Action, 3rd edition