Here is the definition of
static <T> int binarySearch(List<? extends Comparable<? super T> list, T key)
static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
static <T extends Comparable<? super T>> int binarySearch(List<T> list, T key)
static <T> int binarySearch(List<T>, T x, Comparator<? super T>)
The first set of signatures is slightly more general. It works in odd edge-cases, which the second would reject. Consider the case of
import java.sql.Timestamp; // extends Date implements Comparable<Date> (!) import java.util.Date; List<Timestamp> timestamps = ...; Date key = ...; int index = Collections.binarySearch(timestamps, key);
This works for the first signature, but would be rejected as a type error under the second (you'd have to convert the
key into a
This may be a rare thing, but as the example of
Date shows, there are examples of this in the JDK.
Maybe, it helps to remember, that
binarySearch never needs to compare elements of the lists with other elements of the list. It only ever compares an element of the list with the given
key, and thus, it makes sense, to require, that the list elements are comparable with the
key (and not necessarily with each other).