I spent time yesterday on a tricky bug. After a “long” one hour fight I finally found the cause of the problem. It was just a misunderstanding from myself of the java.util.Collections.bynarySearch method :

public static <T> int binarySearch(List<? extends T> list,
                                   T key,
                                   Comparator<? super T> c)

According to the contract of this method the return value will be >= 0 if and only if the key is found.

I was thinking that it was equivalent to say: “list.contains(key) is true”. I was wrong !!!! It really means if the key is found using the given comparator; i.e if the method return 0 !!!

I am learning Java every day ;o) and it’s just another silly young Java developer problem that will no more make me waste time.


2 thoughts on “java.util.Collections.binarySearch

  1. Erm… forgive my ignorance but why else would you provide a comparator? Of course this method uses the comparator for comparison. That’s the whole point of this method, isn’t it?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s