-->

ConcurrentModificationException and HashSet.iterat

2019-05-10 21:28发布

问题:

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.