Vector 上的并发修改错误

发布于 2024-11-03 21:00:34 字数 680 浏览 5 评论 0原文

我在这里想要完成的是每当检测到碰撞时从向量中删除“花”。但是,我不断收到 ConcurrentModificationError。当我尝试从矢量中移除花朵时,情况变得一团糟。我尝试过很多方法。当检测到应该删除花朵时,我将其位置保存在向量中,然后在查看列表中的下一个位置时尝试将其删除。我认为这是您需要看到的唯一方法。有人能看到我能做些什么来解决这个问题吗?

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

                }
    }
}

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

                }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温柔嚣张 2024-11-10 21:00:34

解决方案是使用迭代器并在 Vector 上进行同步。

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

    }  
}  

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

    }  
}  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文