我一直在尝试获取列表的子集,将其反转,然后将反转后的列表放回起始位置。例如,假设我们有列表[1, 2, 3, 4, 5, 6]
,然后从索引2反转到索引4将得到[1, 2, 5, 4, 3, 6]
。
我已经为此编写了一些代码,但是每次都会给出ConcurrentModificationException(除非startIndex == endIndex)。下面提供了一个最小的可复制示例:
int startIndex = 2;
int endIndex = 4;
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
List<Integer> toReverse = list.subList(startIndex, endIndex+1);
Collections.reverse(toReverse);
list.removeAll(toReverse);
list.addAll(startIndex, toReverse);
线程“主”中的异常java.util.ConcurrentModificationException在java.util.ArrayList $ SubList.checkForComodification中(未知源)在java.util.ArrayList $ SubList.size(未知源)在java.util.AbstractCollection.toArray(未知源)java.util.ArrayList.addAll(未知源)在test.ConcurrentExample.main(ConcurrentExample.java:64)
错误所指的实际行是list.addAll(startIndex, toReverse);
。
我不确定是什么问题,因为迭代过程中似乎没有任何变化。如果有人可以解释why的情况和/或how进行修复,将不胜感激。