微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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).此方法根据元素的自然顺序对元素进行排序.所以没有使用比较器.

原文地址:https://www.jb51.cc/java/129497.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐