21

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

Mechanical snail
  • 29,755
  • 14
  • 88
  • 113
Joel
  • 339
  • 2
  • 11
  • You have same situation at other places in the Java api, e.g. the ObjectOutputStream which expects an Object implementing Serializable. I guess, the developers tried to prevent us from doing unecessary casts. – ZeissS Feb 11 '10 at 18:24
  • Back in the day, there were multiple people implementing JDK's, not just Sun. Implementations of the class may have desired the Comparable, but allowed any deterministic, stable sort. (Hypothetically speaking) – Kylar Feb 11 '10 at 18:38

2 Answers2

9

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 :)

Alexander Torstling
  • 18,552
  • 7
  • 62
  • 74
  • "you cannot just cast it to Comparable[] if the original type was Object[]" - but *why should I expect* to be able to call it with an `Object[]`? If it's an intentional design constraint of the program that the array should only contain `Comparable`s, why wouldn't I create and use a `Comparable[]` in the first place? – Karl Knechtel Feb 14 '23 at 17:38
4

Otherwise you can't pass Object[] in.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    @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 Faust Feb 11 '10 at 18:34
  • 6
    There are still a lot of `toArray()` like methods in Java API which returns `Object[]`. – BalusC Feb 11 '10 at 18:36
  • 1
    They could be implementing `Comparator`, which is similar, but not the same as `Comparable` – chama Feb 11 '10 at 19:59