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

java – 排序的ConcurrentModification异常

发布时间:2020-12-15 04:39:45 所属栏目:Java 来源:网络整理
导读:我写了这个小程序来排序数组.根据我的理解,它应该打印0,1,2. 但是,当我运行此程序时,我收到ConcurrentModificationException public class Test { public static void main(String[] args) { ListDouble l1 = new ArrayListDouble(Arrays.asList(2.,0.,1.));
我写了这个小程序来排序数组.根据我的理解,它应该打印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时),如代码所示.

(编辑:李大同)

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

    推荐文章
      热点阅读