为什么Arrays.sort取Object []而不是Comparable []? [英] Why does Arrays.sort take Object[] rather than Comparable[]?

查看:154
本文介绍了为什么Arrays.sort取Object []而不是Comparable []?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么Arrays类的排序方法要求一个Object []类型的参数。为什么参数不是类型Comparable []。如果你没有传递一个Comparable []它产生一个ClassCastException。

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.

为什么... public static void sort(Object [] a)而不是 public static void sort(Comparable [] a)
感谢

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

推荐答案

因为第二种形式需要重新分配数组。即使你知道你的数组只包含可比较,如果原始类型是Object [],你不能将它转换为Comparable [],因为数组类型不匹配。

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.

您可以:

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

但你不能这样做:

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

所以这是过早的优化:)

So it's premature optimization :)

这篇关于为什么Arrays.sort取Object []而不是Comparable []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆