加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 00:41:49 所属栏目:Java 来源:网络整理
导读:我有一个项目,教授给了我们一些代码.代码中有一行让我困惑: arrayListName.sort(null); 对sort(null)的调用究竟做了什么? 文档说:“如果指定的比较器为null,则此列表中的所有元素必须实现Comparable接口,并且应该使用元素的自然顺序.此列表必须是可修改的
我有一个项目,教授给了我们一些代码.代码中有一行让我困惑:
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).此方法根据元素的自然顺序对元素进行排序.所以没有使用比较器.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读