Search code examples
javaarrayssortingcomparatorcomparable

Why does sort take an Object array?


I just stumbled upon the following overloads of sort in java.util.Arrays:

public static void sort(Object[] a)

public static <T> void sort(T[] a, Comparator<? super T> c)

Why is the first overload not generic, but the second one is? Why does the first overload take an Object[] instead of a Comparable[]? The documentation even states:

All elements in the array must implement the Comparable interface.

So what's the point of not verifying that constraint with Java's static type system?


Solution

  • The first method could be better if it were generic, but it would break compatibility with pre 1.5 code:

    static <T extends Comparable<T>> void sort(T[] a) {
        ...
    }
    
    static void main(String[] args) {
       Object[] a = {"1", "2"};
       sort(a); <- compile time error, need explicit cast sort((Comparable[])a);
    }
    

    While the second one compiles with 1.4 code with warning only

    public static <T> void sort(T[] a, Comparator<? super T> c) {
        ...
    }
    
    public static void main(String[] args) throws Exception {
        Object[] a = { "1", "2" };
        sort(a, new Comparator() {   <-- warning 
            @Override
            public int compare(Object o1, Object o2) {
                return 0;
            }
        });
    }