Java – why does one loop throw a concurrentmodificationexception while the other does not?
•
Java
I encountered this problem when I was writing a travel salesman plan For the inner loop, I tried one
for(Point x:ArrayList<Point>) { // modify the iterator }@H_301_3@但是当向该列表添加另一个点时会导致ConcurrentModicationException被抛出.
但是,当我将循环更改为
for(int x=0; x<ArrayList<Point>.size(); x++) { // modify the array }@H_301_3@循环运行良好,不会抛出异常.
一个for循环,那么为什么一个抛出异常而另一个没有?
Solution
As others have explained, iterators detect changes to the underlying collection, which is a good thing because it can lead to unexpected behavior
Imagine this set of code modifications without iterators:
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 } }@H_301_3@
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码