java.util.Collections.binarySearch

June 6, 2008

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 comparator.compare() 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.