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

后端 未结 5 1713
余生分开走
余生分开走 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:43

    If you run the code and observe you find that first iteration of the loop works fine but the second throws ConcurrentModicationException

    if is because next() method checks if the number of the elements did not change.

    For nice explanation see http://javaadami.blogspot.com/2007/09/enhanced-for-loop-and.html

提交回复
热议问题