在同一arraylist上使用addall和removeall的并发修改异常 [英] concurrent modification exception on using addall and removeall on same arraylist
问题描述
我必须从 ArrayList
中删除一个子列表,并在开始时添加一个子列表.我正在使用以下代码-
I have to remove a sublist from the ArrayList
and add the same in begining. I am using below code -
for(int i =0 ;i <m ; i++){
List<Integer> t = q.subList(j, k);
q.removeAll(t);
q.addAll(0, t);
}
我正在 addAll
上进行并发异常修改.我尝试从q创建一个副本列表,然后在其上调用 addAll
,但仍然在同一行上引发错误.
I am getting concurrent exception modification on addAll
. I tried creating a copy list from q and then calling addAll
on that, still it throws the error on same line.
for(int i =0 ;i <m ; i++){
List<Integer> t = q.subList(j, k);
q.removeAll(t);
ArrayList<Integer> q1= new ArrayList<Integer>(q);
q1.addAll(0, t);
}
如何在同一数据列表上执行这两项操作?
How can I perform both actions on same data list?
推荐答案
subList
的Javadoc指出:
The Javadoc of subList
states that:
如果后备列表(即此列表)以结构方式(而不是通过返回的列表)进行了修改,则此方法返回的列表的语义将变得不确定.(结构修改是指更改此列表的大小的结构修改,或以其他方式扰乱此列表的方式,以至于正在进行的迭代可能会产生错误的结果.)
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.)
这意味着调用 removeAll
可能会使 subList
返回的列表无效.
This means calling removeAll
may invalidate the list returned by subList
.
此外, addAll
的Javadoc指出:
In addition, the Javadoc of addAll
states that:
如果在操作进行过程中修改了指定的集合,则此操作的行为是不确定的.(请注意,如果指定的集合是此列表,并且是非空的,则将发生.)
在您的情况下,您要传递给 addAll
的 Collection
是子列表,该列表由原始的 List
支持您正在呼叫 addAll
.
And in your case, the Collection
you are passing to addAll
is the sub-list, which is backed by the original List
on which you are calling addAll
.
您可以做的是将子列表的元素存储在单独的 List
( copyOfSubList
)中,使用 clear()
删除子列表的元素(这也会从原始的 List
中删除它们),然后将 copyOfSubList
的元素添加回原始的 List 代码>:
What you can do is store the elements of the sub-list in a separate List
(copyOfSubList
), use clear()
to remove the elements of the sub-list (which will remove them also from the original List
) and then add the elements of copyOfSubList
back to the original List
:
for(int i =0 ;i < m ; i++) {
List<Integer> t = q.subList(j, k);
List<Integer> copyOfSubList = new ArrayList<> (t);
t.clear ();
q.addAll(0, copyOfSubList);
}
这篇关于在同一arraylist上使用addall和removeall的并发修改异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!