Why does Arrays.sort take Object[] rather than Comparable[]?

限于喜欢 提交于 2019-12-18 03:56:29

问题


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:


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




回答2:


Otherwise you can't pass Object[] in.



来源:https://stackoverflow.com/questions/2246615/why-does-arrays-sort-take-object-rather-than-comparable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!