java - 子列表抛出的 ConcurrentModificationException

标签 java list

<分区>

我有非常简单的代码:

    List<String> list = new ArrayList<String>();
    String a = "a";
    String b = "b";
    String c = "c";
    String d = "d";

    list.add(a);
    list.add(b);
    list.add(c);

    List<String> backedList = list.subList(0, 2);
    list.add(0, d); 
    System.out.println("2b: " + backedList);

我通过 list.add(0, d) 得到了 ConcurrentModificationException 异常。所以一般来说,是因为sublist()。我很困惑,因为在 sublist() 的情况下,文档说:

The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

你能解释一下问题在哪里吗?

最佳答案

subList 是原始列表的简单 View (参见 here )。您可以改变其中的元素,但不能更改列表的结构。

根据文档,如果您尝试进行结构更改,subList 行为是未定义的。我想在这个特定的实现中,ConcurrentModificationException 被确定为未定义的行为。

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.)

关于java - 子列表抛出的 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8817608/

相关文章:

java - 在我不知道类型的对象上调用方法

java - 如何使用java从mongodb中完整测试搜索的结果中获取特定字段

c# - 在 C# 中,如果将列表中的对象添加到另一个列表中,更改第二个列表中的对象是否会更改第一个列表中的同一对象?

python - 在 python 中的列表中交换元组/列表中的值?

c++ - 数组/指针列表 C++

java - 在枚举中使用字符串资源并在 switch case 中使用

java - 使用路标发送由 OAuth 验证的 POST 请求时出错

java - Java 中的泛型,Merge 方法

python - 为什么 list() 与一个对象分别显示不同的结果?

list - 如何更新 Scheme (Racket) 中的列表