ConcurrentModificationException and HashSet.iterator()

Jiew Meng picture Jiew Meng · Sep 24, 2012 · Viewed 11.4k times · Source

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?

Answer

Petter picture Petter · Sep 24, 2012

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