问题
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);
}
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?
回答1:
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.)
This means calling removeAll
may invalidate the list returned by subList
.
In addition, the Javadoc of addAll
states that:
The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (Note that this will occur if the specified collection is this list, and it's nonempty.)
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
.
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);
}
回答2:
You can use CopyOnWriteArrayList instead of ArrayList
.
Iterators of CopyOnWriteArrayList
never throw ConcurrentModificationException
. When an iterator is created, it keeps a copy of the list's contents.
来源:https://stackoverflow.com/questions/44744092/concurrent-modification-exception-on-using-addall-and-removeall-on-same-arraylis