Why does Arrays.sort take Object[] rather than Com

2019-03-23 15:03发布

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条回答
在下西门庆
2楼-- · 2019-03-23 15:31

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

查看更多
放我归山
3楼-- · 2019-03-23 15:56

Otherwise you can't pass Object[] in.

查看更多
登录 后发表回答