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);
}
}
}
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 iteratorwhile iterating instead of callinglist.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.