java - CompareTo 方法如何与 array.sort 一起使用来对数组进行排序?

标签 java arrays sorting compareto

我知道compareTo可以返回正负值和零值。

所以如果我使用

public class x implements Comparable <Object O> {/*...*/}

并在里面赋值

public int compareTo(int i) {       
    if (this.intg < i) { return -1; } 
    else if (this.intg > i) { return 1; } 
    else { return 0; }
}

我可以通过这种方式使用 sort Array.sort(O[]objects) 吗?

我不知道array.sort()compareTo()的联系。 它甚至不调用compare方法来对其进行排序。 那么 compareTo() 输入的真正作用是什么?使用array.sort()时无法调用该方法,该传到哪里去

最佳答案

这是 Arrays.sort(Object[]) 的 Javadoc :

Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface. Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

因此排序方法确实依赖于数组元素的 Comparable 接口(interface)。

关于java - CompareTo 方法如何与 array.sort 一起使用来对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32810789/

相关文章:

java - Spring boot - 有没有办法为给定的配置文件禁用 AOP?

javascript - 将对象数组减少/过滤为新的对象数组。

jquery - 从 jquery 中的另一个数组创建一个项目数组

php - 从多行中选择Mysql数据,算术,排序

算法 - 根据两个标准平均填充不同大小的容器

.net - 如果 DataGrid 列已排序(而不是排序),我如何收到通知

java - 如何在 javafx 的 imageView 中填充图像?

java - 当excel单元格中没有值时,显示错误

Java:如何将 com.google.api.services.drive.model.File 转换为 InputStream?

arrays - 无法让数组在 Mac 上的 Office 365 Excel 中工作