'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 的 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?

自然排序是由 ComparablecompareTo 定义的排序。例如,Integer自然地从最低值到最高值排序。

`Does natural ordering of primitives and reference types differ and if so how?

从技术上讲,没有。基元的自然顺序(doubleboolean 与其包装器 classes(DoubleBoolean)的顺序相同。

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