Reputation: 115
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);
}
}
}
Upvotes: 0
Views: 428
Reputation: 66637
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.
Upvotes: 1
Reputation: 26574
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.
Upvotes: 0