java – arrayListName.sort(null)做什么?

我有一个项目,教授给了我们一些代码.代码中有一行让我困惑:
arrayListName.sort(null);

对sort(null)的调用究竟做了什么?

文档说:“如果指定的比较器为null,则此列表中的所有元素必须实现Comparable接口,并且应该使用元素的自然顺序.此列表必须是可修改的,但不需要可调整大小.”这个列表的自然顺序是什么意思?我们尝试排序的元素是电话号码.

注意:我读了javadoc并且我不清楚这是什么意思.英语不是我的第一语言,教授不用英语授课.我试图谷歌这个问题,但我仍然感到困惑,具体是什么意思.

解决方法

说明

假设arrayListName实际上是ArrayList类型的变量,那么你在这里调用List#sort方法.从它的documentation

default void sort(Comparator<? super E> c)

Sorts this list according to the order induced by the specified Comparator.

If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements’ natural ordering should be used.

因此,当比较器为空时,该方法使用元素的自然排序.

这些自然顺序由项目上的compareto方法实现,它们实现了Compareable接口(documentation).对于int,这种情况越来越多.对于String,这基于lexicographical order进行排序.

使用自然排序排序后的示例:

1,2,3,8,11

"A","B","H","Helicopter","Hello","Tree"

许多类已经实现了这个接口.看看documentation.目前它有287个班级.

细节

让我们将它与实际的implementation进行比较:

@Override
@SuppressWarnings("unchecked")
public void sort(Comparator<? super E> c) {
    final int expectedModCount = modCount;
    Arrays.sort((E[]) elementData,size,c);
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}

比较器c传递给方法Arrays#sort,让我们看一下implementation的摘录:

if (c == null) {
    sort(a,fromIndex,toIndex);
}

我们跟着调用一个Arrays#sort方法(implementation).此方法根据元素的自然顺序对元素进行排序.所以没有使用比较器.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...