0

I have an ArrayList containing StoreItem objects with specific names such as gum, socks, candy etc. I need to iterate the ArrayList and remove specific objects based on their name provided in the method's parameters...public void removeItem(String itemtoremove) How do I do this without getting the CME?

public void removeItem(String itemtoremove) {
   for (StoreItem anItem: this.store) {
       if (anItem.getName().equals(itemtoremove) {
            this.store.remove(anItem);
       }
    }
}
digitaljoel
  • 26,265
  • 15
  • 89
  • 115
Ryan Peters
  • 115
  • 1
  • 11
  • possible duplicate of [Calling remove in foreach loop in Java](http://stackoverflow.com/questions/1196586/calling-remove-in-foreach-loop-in-java) – Thilo Aug 24 '12 at 03:05
  • This is a classic coding error: You need an iterator to remove. It is also an exact duplicate - please close this, people. – Bohemian Aug 24 '12 at 03:14
  • I'm sorry about the duplicate question. I'll try to be more thorough in my next search. cheers – Ryan Peters Aug 24 '12 at 03:25

2 Answers2

1

You didn't post related code so it is hard to tell what is wrong with your code

But, one of the way to avoid CME is

call remove() on iterator while iterating instead of calling list.remove(obj)

EDIT:

Don't use for:each, use iterator to iterate over the list and then call remove() on iterator whenever you want to perform delete.

kosa
  • 65,990
  • 13
  • 130
  • 167
  • Which is the only way to remove while iterating. Unfortunately, this does not let you remove arbitrary objects ("based on their name"), but just the current one. (Which does not seem to be a problem here, seeing the updated question) – Thilo Aug 24 '12 at 03:00
0

The documentation states:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

So make sure you are only calling the iterator's remove method.

digitaljoel
  • 26,265
  • 15
  • 89
  • 115