Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java ArrayList remove object while iterating [duplicate]

I'm running an iterator over an arraylist and am trying to remove an item when a condition is true.

I have the following code:

String item = (String) model.getElementAt(selectedIndices[i]);
Iterator it = p.eggMoves.iterator();
while(it.hasNext())
{
    String text = (String) it.next();
    if ( text.equals(item) )
    {
        it.remove();
        p.eggMoves.remove(selectedIndices[i]);
        model.removeElementAt(selectedIndices[i]);
    }
}

Now this code works fine, the item is removed from both the p object and the jlist, but it throws an "ConcurrentModificationException" exception at the it.next() line.

How do I solve this?

like image 578
Ceri Turner Avatar asked May 22 '14 22:05

Ceri Turner


People also ask

How can we remove an object from ArrayList while iterating?

The right way to remove objects from ArrayList while iterating over it is by using the Iterator's remove() method. When you use iterator's remove() method, ConcurrentModfiicationException is not thrown.

Can I remove element from list while iterating Java?

An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.


2 Answers

Just remove the item by using it.remove() while iterating.

Below line is causing the issue

p.eggMoves.remove(selectedIndices[i]);

What you want to do by removing same item (that is at index i) again and again?

like image 79
Braj Avatar answered Oct 16 '22 16:10

Braj


There is no need to call both it.remove(); and p.eggMoves.remove(selectedIndices[i]);. The call to it.remove(); will remove the current item from p.eggMoves.

Remove the call to p.eggMoves.remove(selectedIndices[i]); and it should work fine.

like image 31
rgettman Avatar answered Oct 16 '22 16:10

rgettman