【问题标题】:Need to understand ConcurrentUpdateException after sorting?排序后需要了解 ConcurrentUpdateException 吗?
【发布时间】:2017-04-24 05:59:03
【问题描述】:

我编写了一个抛出 ConcurrentUpdateException 的程序,我无法理解这种行为,它不应该出现任何异常,因为我只有一个线程可以使用并且我没有使用任何迭代器。

在排序中会发生什么?为什么会抛出这个异常?请解释一下。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

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

    }
}

【问题讨论】:

  • 你能添加堆栈跟踪吗? 3., 2., 0., 1., 2. 是什么?
  • 在本地为我执行代码时也不例外。它只输出0.0
  • 正如@Sergey 指出的那样, subList() 返回一个由原始列表支持的视图。对原始列表的任何结构更改都会使视图未定义(例如,如果您希望子列表中的原始列表的元素 0 到 3 并且您对原始列表进行排序,则这些元素将不再是您最初的元素要求)。 ConcurrentUpdateException 有点误导,因为它似乎表明存在多线程问题。相反,当对父列表修改的显式测试为肯定时,它会被抛出。

标签: java arrays list concurrentmodification


【解决方案1】:

函数subList 返回此列表中指定范围的视图。所以当你对集合进行排序时,subList 也会发生变化。这就是为什么你得到0.0,而不是3.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 2012-03-11
    相关资源
    最近更新 更多