Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentModificationException thrown on for each in android

i passing list of tags in forloop for iterate but its raised ConcurrentModificationException

 public void clearTag() {
    List<Tag> tags = binding.search.tagView.getTags();
    Log.d(TAG, "clearTags: " + tags);
    for (Tag tag : tags) {
        Log.d(TAG, "clearTag: " + tag + " " + tag.getLayoutColor());
        if (tag.getLayoutColor() == R.color.red) {
           tags.remove(tag);
        } else if (tag.getLayoutColor() == R.color.blue) {
            tags.remove(tag);
        } else if (tag.getLayoutColor() == R.color.green) {
            tags.remove(tag);
        }
    }
    updateTagVisibility();
    //resetFilter();
}
like image 221
sam Avatar asked May 30 '26 01:05

sam


1 Answers

This is because remove and add operations are not allowed while iterating through an array. So you need to store all elements to remove in different array, then remove them at once. Here is an example:

public void clearTag() {
    List<Tag> tags = binding.search.tagView.getTags();
    List<Tag> tagsToRemove = new ArrayList<>();
    Log.d(TAG, "clearTags: " + tags);
    for (Tag tag : tags) {
        Log.d(TAG, "clearTag: " + tag + " " + tag.getLayoutColor());
        if (tag.getLayoutColor() == R.color.red) {
           tagsToRemove.add(tag);
        } else if (tag.getLayoutColor() == R.color.blue) {
            tagsToRemove.add(tag);
        } else if (tag.getLayoutColor() == R.color.green) {
            tagsToRemove.add(tag);
        }
    }
    tags.removeAll(tagsToRemove);
    updateTagVisibility();
    //resetFilter();
}
like image 183
Yev Kanivets Avatar answered May 31 '26 14:05

Yev Kanivets



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!