File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Concurrent Modification Exception during delete loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Concurrent Modification Exception during delete loop" Watch "Concurrent Modification Exception during delete loop" New topic

Concurrent Modification Exception during delete loop

kwame Iwegbue
Ranch Hand

Joined: Sep 02, 2000
Posts: 197
I'm getting a java.util.ConcurrentModificationException during this code:

The line throwing the exception i think is:

The API says basically that this is caused by removing an item while iterating through a fail-fast collection. Not sure what this means, or how I can fix it. Any ideas?

Who dares, wins! (SAS motto)
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
The documentation for this error isn't very good, unfortunately. The problem is that you are calling remove() directly on the collection while you are iterating that collection. If you want to modify a collection while iterating through it, you should use methods of the iterator, not of the collection. In this case you don't see the Iterator, because it's hidden by the for loop. However to do what you want, you will have to replace the loop with an old-fashioned iteration loop, so that you can see the iterator:

Here the key point is that we're no longer using getPatients().remove(patient) - we're using it.remove(). The Iterator knows how to safely remove objects while iterating. The Collection doesn't.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Concurrent Modification Exception during delete loop
It's not a secret anymore!