排序时的 ConcurrentModification 异常

ConcurrentModification Exception on Sorting

我写了这个小程序来排序arrays。据我了解,它应该打印 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 上有而不是 JAVA7

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 时),如您的代码所示。

List.sublist returns 部分列表的视图,因此您不能修改原始列表。如果你想让它工作,那么你需要将子列表重写为一个新的列表对象:

        List<Double> l1 = new ArrayList<>(Arrays.asList(2.0, 0.0, 1.0));
        List<Double> l2 = new ArrayList<>(l1.subList(0, 3));
        Collections.sort(l1);
        System.out.println(l2.get(0));

否则 l2 值会在排序操作后改变,这是不需要的,java 不允许。