Monday, July 25, 2011

java.util.ConcurrentModificationException with ArrayList

You will receive java.util.ConcurrentModicationException error, if you are modifying a list while iterating it. For example, the following code will throw you the exception:

for (Object obj : list) {
  if (obj.getCode().equals("something"))
    list.remove(obj);
}


To avoid this exception, the trick is to delete/add an item through the iterator, but not the collection. Here is the example:

Iterator it = list.iterator();
while (it.hasNext()) {
  Object obj = (Object)it.next();
  if (obj.getCode().equals("something")) {     

    it.remove();
  }
}


Hope this helps.

2 comments:

Anonymous said...

excellent article. But I need more written

norbstar on January 23, 2012 at 2:53 AM said...

Great article; short, concise, to the point and accurate. Nice one.

 

Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template