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);
       }
    }
}
3
  • possible duplicate of Calling remove in foreach loop in Java Commented Aug 24, 2012 at 3:05
  • This is a classic coding error: You need an iterator to remove. It is also an exact duplicate - please close this, people. Commented Aug 24, 2012 at 3:14
  • I'm sorry about the duplicate question. I'll try to be more thorough in my next search. cheers Commented Aug 24, 2012 at 3:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.