gpt4 book ai didi

java - 排序时的 ConcurrentModification 异常

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:21:34 25 4
gpt4 key购买 nike

我写了这个小程序来对数组进行排序。据我了解,它应该打印 0,1,2

但是,当我运行这个程序时,我得到了 ConcurrentModificationException

    public class Test {
public static void main(String[] args) {
List<Double> l1 = new ArrayList<Double>(Arrays.asList(2., 0., 1.));
List<Double> l2 = l1.subList(0, 3);
Collections.sort(l1);
System.out.println(l2.get(0));
}
}

我真的不确定这个异常的根本原因。

有人可以帮助我了解我哪里出错了吗?

注意:这个问题在 JAVA 7 上不存在,如果有人也告诉为什么它在 JAVA 8 中而不在 JAVA 7 中存在,那就太好了

最佳答案

List.subList的API文档说:

The semantics of the list returned by this method become undefined if the backing list (i.e., this list) is structurally modified in any way other than via the returned list. (Structural modifications are those that change the size of this list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)

排序确实会以这样一种方式更改列表,即进行中的迭代会导致不正确的结果。 API 文档说在这种情况下发生的事情是未定义的 - 实际上这意味着 ConcurrentModificationException 被抛出(至少,在使用 Java 8 时),如您的代码所示。

关于java - 排序时的 ConcurrentModification 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45209540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com