[英]Iteration error when started from 1st one to last one i.e in normal way
@Override
public boolean onTouchEvent(MotionEvent event)
{
if (System.currentTimeMillis() - lastClick > 300)
{
lastClick = System.currentTimeMillis();
synchronized (getHolder()) {
for (int i = sprites.size() - 1; i >= 0; i--) <-------why in reverse?
{
Sprite sprite = sprites.get(i);
if (sprite.isCollition(event.getX(), event.getY()))
{
sprites.remove(sprite);
break;
}
}
}
But when i iterate from lastone to firstone ie in reverse order it gives the result.why ..? 但是,当我从lastone迭代到firstone时,即以相反的顺序,它会给出结果。为什么..? Need help 需要帮忙
It's because you are removing the sprites while inside the for loop. 这是因为要在for循环中删除精灵。 When you alter the number of objects in the loop when moving forward, you stuff up the iteration. 向前移动时,如果更改循环中的对象数,则会填充迭代。 When you remove the current element, all elements found in the list after this element (and still to be enumerated through) are now shifted down an index, ie the element that was at index i+1
is now at index i
. 当您删除当前元素时,在列表中找到的该元素之后的所有元素(并且仍要进行枚举)现在都下移一个索引,即位于索引i+1
处的元素现在位于索引i
。
If you are removing from the loop you are iterating through, the correct way is to iterate in reverse, like you have found out. 如果要从循环中删除,则正确的方法是像发现的那样反向进行迭代。 That way when you remove the current element, all other elements to still be enumerated through are still at the same index. 这样,当您删除当前元素时,所有其他仍要枚举的元素仍位于同一索引处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.