views:

148

answers:

2

I was wondering why the sort method of the Arrays class is asking for a parameter of type Object[]. Why the parameter is not of type Comparable[]. If you don't pass a Comparable[] it's generating a ClassCastException.

Why ... public static void sort(Object[] a) and not public static void sort(Comparable[] a) ? Thanks

+1  A: 

Otherwise you can't pass Object[] in.

BalusC
@BalusC Is there ever a situation where you would pass to sort an array of Objects that you didn't know were all implementing `Comparable`? Any use of the sort method will be by objects that are `Comparable`. Seems like the only reason for accepting `Object[]` is that `Object` is used more frequently and is more familiar, and like ZeissS said, otherwise we would have to cast.
Jonathon
There are still a lot of `toArray()` like methods in Java API which returns `Object[]`.
BalusC
They could be implementing `Comparator<T>`, which is similar, but not the same as `Comparable<T>`
chama
+2  A: 

Because the second form would require a reallocation of the array. Even if you know that your array contains only comparables, you cannot just cast it to Comparable[] if the original type was Object[], since the array type does not match.

You can do:

Object[] arr = new String[0];
String[] sarr = (String[]) arr;

But you can't do:

Object[] arr = new Object[0];
String[] sarr = (String[]) arr;

So it's premature optimization :)

disown