'natural ordering' 的含义及其与 compareTo() 方法的关系
The meaning of 'natural ordering' and its relation to the compareTo() method
在回顾 Java 中的数组主题时,我在 java.util
包的 Arrays
class 中遇到了以下方法。
void sort(type[] array)
此外,我偶然发现了一些事情,我觉得需要更多解释。
The method sorts the elements in the array according to their
natural ordering.
我试着在下面总结一下我对此的疑惑:
自然顺序的确切含义是什么?
原始类型和引用类型的自然排序是否不同?如果不同,有何不同?
最后,Comparable<T>
接口的compareTo()
方法如何定义and/or覆盖自然顺序?
当我们对扩展 Comparable
的 class 实例进行排序时,我们谈论 自然排序 ,这要归功于 compareTo(T o)
的实现。
检查 Comparable
的 javadoc:
This interface imposes a total ordering on the objects of each class
that implements it. This ordering is referred to as the class's
natural ordering, and the class's compareTo
method is referred to as its natural comparison method.
What is meant precisely by natural ordering?
自然排序是由 Comparable
的 compareTo
定义的排序。例如,Integer
自然地从最低值到最高值排序。
`Does natural ordering of primitives and reference types differ and if so how?
从技术上讲,没有。基元的自然顺序(double
、boolean
与其包装器 classes(Double
、Boolean
)的顺序相同。
How does compareTo()
method of the Comparable
interface define and/or override natural ordering?
compareTo
定义了 class 的自然顺序,这就是 Javadoc 解释 "All elements in the array must implement the Comparable interface."
的原因
作为旁注,通过为执行排序的情况定义 Comparator
来覆盖自然排序。例如,您可以根据需要使用 Arrays.sort(T[], Comparator<? super T>)
对 String[]
进行排序(在这种情况下,通用 T
将变为 String
)。
在回顾 Java 中的数组主题时,我在 java.util
包的 Arrays
class 中遇到了以下方法。
void sort(type[] array)
此外,我偶然发现了一些事情,我觉得需要更多解释。
The method sorts the elements in the array according to their natural ordering.
我试着在下面总结一下我对此的疑惑:
自然顺序的确切含义是什么?
原始类型和引用类型的自然排序是否不同?如果不同,有何不同?
最后,
Comparable<T>
接口的compareTo()
方法如何定义and/or覆盖自然顺序?
当我们对扩展 Comparable
的 class 实例进行排序时,我们谈论 自然排序 ,这要归功于 compareTo(T o)
的实现。
检查 Comparable
的 javadoc:
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's
compareTo
method is referred to as its natural comparison method.
What is meant precisely by natural ordering?
自然排序是由 Comparable
的 compareTo
定义的排序。例如,Integer
自然地从最低值到最高值排序。
`Does natural ordering of primitives and reference types differ and if so how?
从技术上讲,没有。基元的自然顺序(double
、boolean
与其包装器 classes(Double
、Boolean
)的顺序相同。
How does
compareTo()
method of theComparable
interface define and/or override natural ordering?
compareTo
定义了 class 的自然顺序,这就是 Javadoc 解释 "All elements in the array must implement the Comparable interface."
作为旁注,通过为执行排序的情况定义 Comparator
来覆盖自然排序。例如,您可以根据需要使用 Arrays.sort(T[], Comparator<? super T>)
对 String[]
进行排序(在这种情况下,通用 T
将变为 String
)。