简体   繁体   中英

How to avoid a ConcurrentModificationException when removing objects from an ArrayList

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM