尝试从ArrayList中删除对象时崩溃

use*_*313 0 crash android arraylist object

我有一个问题,我还没有找到解决方案.我正在制作一个小游戏,如果与另一个名为ball的对象相撞,_sballs ArrayList中的对象将被删除.我遇到的问题是,当碰撞发生时,当我尝试从ArrayList中删除对象时,应用程序崩溃.

for(GObject sballgraphic : _sballs){
            Coordinates sballcoords = sballgraphic.getCoords();
            if(coords.getY() - coords._height > sballcoords.getY() + sballcoords._height && coords.getX() - coords._width > sballcoords.getX() + sballcoords._width){
                _sballs.remove(sballgraphic);
            }
        }
Run Code Online (Sandbox Code Playgroud)

因此,代码将球坐标与所有sballs对象进行比较以检查是否存在碰撞,然后尝试移除sball.

这里有什么问题?:)

tru*_*ity 5

我猜测"崩溃"是一个ConcurrentModificationException.

它正在发生,因为当您使用迭代器(增强的for的内部工作)迭代它时,您试图从集合中删除.

你的选择是:

  1. 使用索引迭代(旧式for( i=0; i<_sballs.size(); i++ ))
  2. 显式迭代使用迭代器,并使用迭代器的remove()方法.
  3. 通过将它们放入另一个列表中来记住要删除的项目,然后removeAll()在循环结束后使用.

  • 这是正确的答案,我会选择选项2,因为我认为它是最强大和最干净的解决方案. (2认同)