Search code examples
javaarrayscomparable

Why Arrays.binarySearch(Object[],Object) takes Object args?


The method

public static int binarySearch(Object[] a, Object key) 

of the Arrays class in its implementation navigates through the array argument a following the binarySearch algorithm and converts the elements of a into Comparable and invokes compareTo(key) until it either finds a match or runs out of possibilities.

I'm stumped by the implementation however, if it's the case that the method will always cast the elements to Comparable, and furthermore will throw a ClassCastException if it encounters an element that does not implement Comparable, would it not be clearer for the API user that the method will take into account the comparator of the elements of the array only and not the comparator of the key, be more foolproof by preventing compilation where an invocation was made where the type of the array was not compatible with Comparable, and also execute more efficiently if the method were defined as

public static int binarySearch(Comparable[] a, Object key) 

? What are the advantages to defining the first argument as an array of Object?

EDIT I only saw this after I posted the question and it had been answered but there is a related post here: Why does Arrays.sort take Object[] rather than Comparable[]? where they state that if the method took the parameters (Comparable[], Object) it would not be possible to pass an array of type Object[] to that method without "reallocation" which is also expensive.


Solution

  • See Why does Arrays.sort take Object[] rather than Comparable[]?. The issue is that this would cause problems for arrays that were declared as type Object[] even if they contained only Comparables.