子列表抛出的ConcurrentModificationException [英] ConcurrentModificationException thrown by sublist
问题描述
我的代码非常简单:
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()的情况下文档说:
And I get ConcurrentModificationException exception by list.add(0, d). So in general, it's because of sublist(). I'm very confused, because in case of sublist() the documentation says:
返回的列表由此列表支持,所以非 - 返回列表中
的结构更改将反映在此列表中,反之亦然。
<你能解释一下捕获的位置吗?
Could you explain me where the catch is?
推荐答案
subList
简单的原始列表视图(参见这里)。您可以改变其中的元素,但不能更改列表的结构。
The subList
is simple a view of the original list (see here). You are allowed to mutate elements within it but not change the structure of the list.
根据文档, subList
如果您尝试进行结构更改,则行为未定义。我想在这个特定的实现中, ConcurrentModificationException
被确定为未定义的行为。
According to the documentation, subList
behaviour is undefined if you try to make structural changes. I guess in this particular implementation, ConcurrentModificationException
was decided as the undefined behaviour.
如果支持列表(即此列表)在结构上以除返回列表之外的任何方式进行修改,则此方法返回的列表的语义将变为未定义。 (结构修改是那些改变了这个列表的大小,或以其他方式扰乱它的方式,正在进行的迭代可能会产生不正确的结果。)
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.)
这篇关于子列表抛出的ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!