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

后端 未结 5 1703
余生分开走
余生分开走 2020-12-16 18:40

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

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


        
5条回答
  •  眼角桃花
    2020-12-16 19:41

    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
      }
    }
    

提交回复
热议问题