Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 721
Mishax Avatar asked Oct 12 '13 15:10

Mishax


1 Answers

I think the best declaration would actually be a generic one:

public static <T extends Comparable<? super T>> int binarySearch(T[] a, T key)

My guess is that, simply, this method was created in an early Java version using Objects and could not be changed for reasons of backwards compatibility. This has happened in various other places as well: arrays with their toString() and Cloneable are two noteworthy examples.

like image 75
arshajii Avatar answered Oct 01 '22 14:10

arshajii