user1212520
user1212520

Reputation: 501

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

Upvotes: 2

Views: 185

Answers (3)

Trismegistos
Trismegistos

Reputation: 3882

In case your iterator does not support remove operation you could use following algorithm:

In first step you can iterate over list creating list of indices of elements to be deleted. Next step would be iterating over list of indices backward and deleting elements by index.

Upvotes: -1

dty
dty

Reputation: 18998

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

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1499760

You can use an iterator, but only by abandoning the enhanced for loop:

for (Iterator<MyList> iterator = list.iterator(); iterator.hasNext(); ) {
    MyList ls = iterator.next();
    if (ls.getStatus() == 0) {
        lo.run(zo);
        iterator.remove();
    } else {
        ls.create();
    }
}

Of course, that assumes that list refers to a type which supports the remove operation.

Upvotes: 1

Related Questions