Search code examples
vectorthread-safetyconcurrentmodification

ConcurrentModificationError on Vector


What I am trying to accomplish here is to remove a "blossom" from the Vector whenever a collision is detected. However, I keep getting a ConcurrentModificationError. It messes up when I try to remove the blossom from the Vector. I have tried doing it many ways. At one point when it was detected that the blossom should be removed, I saved its position in the Vector and then tried to remove it when the next position in the list was being looked at. I think this is the only method that you need to see. Can anybody see what I can do to fix this??

private synchronized void DrawBlossoms(Canvas c) // method to draw flowers on screen and test for collision
{
    Canvas canvas = c;
    for(Blossom blossom: blossomVector)
    {
                blossom.Draw(canvas);
                if (blossom.hit(box_x,box_y, box_x + boxWidth, box_y + boxHeight, blossomVector) == true)
                {
                    Log.v(TAG, "REMOVE THIS!");
                    //blossomVector.remove(blossom);

                }
    }
}

Solution

  • The solution is to use an iterator and synchronize on the Vector.

    synchronize(blossomVector)  
    {  
        Iterator dataIterator = blossomVector.iterator();  
        while (dataIterator.hasNext())  
        {  
            //... do your stuff here and use dataIterator.remove()
    
        }  
    }