【问题标题】:Crash when trying to remove object from ArrayList尝试从 ArrayList 中删除对象时崩溃
【发布时间】:2012-04-05 17:16:27
【问题描述】:

我遇到了一个问题,我无法找到解决方案。我正在制作一个小游戏,如果 _sballs ArrayList 中的对象与另一个名为 ball 的对象发生碰撞,将被删除。 我遇到的问题是,当发生冲突时,当我尝试从 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);
            }
        }

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

这里有什么问题? :)

【问题讨论】:

  • 从 logcat 发布堆栈跟踪。

标签: android object crash arraylist


【解决方案1】:

我猜“崩溃”是ConcurrentModificationException

发生这种情况是因为您在使用迭代器迭代集合时尝试从集合中删除(增强 for 的内部工作原理)。

您的选择是:

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

【讨论】:

  • 这是正确的答案,我会选择选项 2,因为我觉得它是最强大和最干净的解决方案。
【解决方案2】:

您无法执行此类操作,因为您正在修改相同的 _sballs,您也正在对其进行迭代。

ArrayList<GObject> _sballs;
ArrayList<GObject> _sballsForRemove;

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){
                _sballsForRemove.add(sballgraphic);
            }
        }
_sballs.removeAll(_sballsForRemove);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 2013-05-05
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多