23

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

2
  • 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. Commented Feb 11, 2010 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) Commented Feb 11, 2010 at 18:38

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

"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 Comparables, why wouldn't I create and use a Comparable[] in the first place?
3

Otherwise you can't pass Object[] in.

3 Comments

@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.
There are still a lot of toArray() like methods in Java API which returns Object[].
They could be implementing Comparator<T>, which is similar, but not the same as Comparable<T>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.