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.curre开发者_如何学CntTimeMillis();
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 i.e in reverse order it gives the result.why ..? Need help
It's because you are removing the sprites while inside the for loop. 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, i.e. the element that was at index i+1
is now at index 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.
精彩评论