我知道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 aClassCastException
for any elementse1
ande2
in the array).
因此排序方法确实依赖于数组元素的 Comparable
接口(interface)。
关于java - CompareTo 方法如何与 array.sort 一起使用来对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32810789/