ConcurrentModificationException and HashSet.iterator()

僤鯓⒐⒋嵵緔 提交于 2019-12-22 09:58:12

问题


I have a for loop like

      for (int neighbour : neighbours) {

Where I may modify neighbours within the loop. Found that thats the cause of ConcurrentModificationException. And read from https://stackoverflow.com/a/8189527/292291

Hence if you want to modify the list (or any collection in general), use iterator, because then it is aware of the modifications and hence those will be handled properly.

So I tried:

neighboursItr = neighbours.iterator();
while (neighboursItr.hasNext()) {
  // try disconnecting vertices
  neighbour = neighboursItr.next();

But that doesnt fix the problem. Why?


回答1:


Are you calling neightbours.remove(neighbour)? In that case, that is the problem. You need to call neightboursItr.remove() instead.




回答2:


Have you considered creating a new HashSet with desired state? I mean you can iterate through the neighbours and add to the newNeighbours whatever you want.




回答3:


You may only modify the collection using methods of the iterator while iterating on the collection. So you may call neighboursItr.remove(), but you may not add an element to the collection using neighbours.add(), for example.




回答4:


You cannot modify collection while iterating. The only exception is using iterator.remove() method (if it is supported by target collection).

The reason is that this is how iterator works. It has to know how to jump to the next element of the collection. If collection is being changed after iterator creation it cannot do this and throws exception.

There are several solutions for this problem. For example if you want to add elements to existing collection during iteration you can create yet another collection where you store new elements and then add all these elements after your iteration is finished.



来源:https://stackoverflow.com/questions/12562548/concurrentmodificationexception-and-hashset-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!