简体   繁体   English

ArrayList.remove()的异常行为

[英]Unexpected behavior with ArrayList.remove()

I have a pizza code that iterates through a list of objects and checks whether they are colliding or not. 我有一个比萨饼代码,它遍历对象列表并检查它们是否碰撞。 If one is collided with, it is removed from the ArrayList. 如果发生冲突,则将其从ArrayList中删除。

for (int i = 0; i < arrayList.size(); i++) {
    Object c = arrayList.get(i);
    if (Rect.intersects(foo.getRect(), c.getRect())) { //Android function, checks if the two rectangles are inside each other.
        foo.setPosY(c.getPosY() + 11); // Always works.
        foo.setVelY(bird.getVelY() * -1); // Always works.
        arrayList.remove(i); // Occasionally fails under special circumcisions.
    }
}

When opening the app fresh for the first time this works fine. 第一次重新打开应用程序时,此方法正常工作。 However, if I exit with the back button and then quickly reopen the app, it will all work except occasionally, removing the object from the ArrayList wont happen. 但是,如果我使用后退按钮退出,然后快速重新打开应用程序,则除了偶尔从ArrayList中删除对象之外其他所有功能都将起作用。

If I close the app and then remove it from the recent apps list, it works. 如果我关闭该应用程序,然后将其从最近的应用程序列表中删除,则它可以工作。 If I exit with the home key, or the back button and then immediately reopen, it sometimes fails to remove the object. 如果我使用Home键或返回按钮退出,然后立即重新打开,则有时无法删除该对象。 I don't understand why this happens, as everything else still works. 我不明白为什么会这样,因为其他所有内容仍然有效。 The two lines of code just before it function just fine. 之前起作用的两行代码就可以了。 I just don't get it. 我就是不明白。

I suspect the problem is that you're skipping an element after one call to remove, because you're incrementing i and everything in the list is moving up one element. 我怀疑问题是您在删除一次调用后就跳过了一个元素,因为您要递增i 列表中的所有内容都在向上移动一个元素。 (It's not really clear what the symptoms are at the moment. If this turns out not to be the problem, it's still a problem.) (这不是真的不清楚什么症状的时刻。如果这个结果并非是问题 ,它仍然是一个问题。)

So if you call remove(2) , the next element you want to look at now has index 2. 因此,如果调用remove(2) ,那么现在要查看的下一个元素的索引为2。

Common ways of fixing this: 解决此问题的常用方法:

  • Work backwards: 向后工作:

     for (int i = arrayList.size() - 1; i >= 0; i--) 
  • Use an iterator instead: 改用迭代器:

     for (Iterator<Foo> iterator = arrayList.iterator(); iterator.hasNext(); ) { Foo c = iterator.next(); if (...) { iterator.remove(); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM