翻译过来就是并发修改异常
代码
for (String s : bank) {//报错行
if (canChange(start, s)) {
bank.remove(s);
dfs(s, end, bank);
bank.add(s);
}
}
报错情况:
Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) at java.util.ArrayList$Itr.next(ArrayList.java:851)
第一样是异常,第二行是异常产生地点,点进去:
private class Itr implements Iterator{ int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification();//在这里发生异常 int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
发现是ArrayList使用迭代器使用异常,使用了不合适的方法修改导致的。结合自己代码报错位置,应该是由于使用forEach遍历的时候修改导致的。
解决
使用forEach遍历进行遍历的时候,底层使用的其实都是对应的迭代器,ArrayList的迭代器是Itr,在迭代过程中发生了普通的修改。
- 不实用forEach和迭代器进行遍历
- 使用迭代器专用的修改方法。
参考:
解决——》Exception in thread “main” java.util.ConcurrentModificationException



