简体   繁体   中英

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 ..? 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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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