Search code examples
javaexceptionconcurrentmodification

concurrent modification exception java, I dont think I can use iterator here?


I have a list I need to iterate over and delete certain items. I can't use an iterator because I need to call methods for each item (such as ls.getStatus()) which doesn't work with an iterator. If ls.getStatus() == 0 I need to delete that item. How can I avoid the ConcurrentModificationException?

for (MyList ls : list) {
    if (ls.getStatus() == 0) {
        ls.run();
        list.remove();
    } else {
        ls.create();
    }
}

Thanks


Solution

  • Why don't you think you can use an iterator?

    Iterator<MyList> i = list.iterator();
    while (i.hasNext()) {
        MyList ls = i.next();
    
        //... all your other code which uses ls...
    
        i.remove();
    }
    

    This approach is also likely to be faster, since using iterator.remove() avoids having to search for the item in the list which is necessary with list.remove(item).