Java – Why use arg type `class Object` instead of `Comparable[]`

interfacesjavaobject-oriented

In the code below, I believe it would look more appropriate to make the method argument be of type Comparable[] instead of Object[].

The first reason it would be more appropriate is that one can be safe from runtime exceptions because every passed object has to implement interface Comparable. Second, every object in Java inherits from class Object so one can typecast any object as (Object) to use the methods of class Object.

package java.util; 
public class Arrays {
.........
public static void sort(Object[] a) {
        Object[] aux = (Object[])a.clone();
        mergeSort(aux, a, 0, a.length, 0);
    }
.........
}

Is there a reason why type Object[] is preferred over type Comparable[] as an argument type?

Best Answer

If you look at the mergeSort code you will see that it casts each member of array a to Comparable. If any object in the array is not a Comparable, a ClassCastException will be generated unless you have created a Comparator which knows how compare your objects and passed that to the sort method. Example of the two different techniques (comparable v comparator) here.

The Java developers decided that you should not be forced to add a Comparable interface to objects just because you want to store them in an array and may choose to sort them at some point. This gives you greater flexibility (and less cruft on your classes) at the minor risk of runtime failures rather than compile-time type checking. The flexibility is a win, in my opinion.

Related Topic