Here is the definition of Collections.binarySearch
in Java:
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)
How do they differ from the following definitions (which are similar to Collections.sort
):
static <T extends Comparable<? super T>> int binarySearch(List<T> list, T key)
static <T> int binarySearch(List<T>, T x, Comparator<? super T>)
As I understand it:
The first definition allows you to search for a key of type T among the list of values, whose type is the same or "lower" of some type that knows how to compare either instances of type T or some "above" type.
The second definition allows you to search for a key of type T among a list of values, whose type is the same or "lower" than type T using a Comparator
that knows how to compare either instances of type T or some "above" type.
Basically, what I do not understand is why aren't list contents enforced to have the same type as the key?