Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

java - Why does one loop throw a ConcurrentModificationException, while the other doesn't?

I've run into this while writing a Traveling Salesman program. For an inner loop, I tried a

for(Point x:ArrayList<Point>) {
// modify the iterator
}

but when adding another point to that list resulted in a ConcurrentModicationException being thrown.

However, when I changed the loop to

for(int x=0; x<ArrayList<Point>.size(); x++) {
// modify the array
}

the loop ran fine without throwing an exception.

Both a for loops, so why does one throw an exception while the other does not?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As others explained, the iterator detects modifications to the underlying collection, and that is a good thing since it is likely to cause unexpected behaviour.

Imagine this iterator-free code which modifies the collection:

for (int x = 0; list.size(); x++)
{
  obj = list.get(x);
  if (obj.isExpired())
  {
    list.remove(obj);
    // Oops! list.get(x) now points to some other object so if I 
    // increase x again before checking that object I will have 
    // skipped one item in the list
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...