ConcurrentModificationException和HashSet.iterator()

Jie*_*eng 3 java iterator concurrentmodification

我有一个for循环

      for (int neighbour : neighbours) {
Run Code Online (Sandbox Code Playgroud)

我可以neighbours在循环内修改的地方.发现那是事业的原因ConcurrentModificationException.并阅读/sf/answers/573266921/

因此,如果您想要修改列表(或一般的任何集合),请 使用迭代器,因为它知道修改,因此将正确处理.

所以我尝试过:

neighboursItr = neighbours.iterator();
while (neighboursItr.hasNext()) {
  // try disconnecting vertices
  neighbour = neighboursItr.next();
Run Code Online (Sandbox Code Playgroud)

但这并没有解决问题.为什么?

Pet*_*ter 9

你在打电话neightbours.remove(neighbour)吗?在那种情况下,这就是问题所在.你需要打个电话neightboursItr.remove().