简体   繁体   中英

Java - For loop only runs once

I recently asked this question: Box2D - Can't destroy multiple fixtures , but figured out it wasn't an issue with Box2D, but an issue with my java. Here is my code:

public static void removeSpecifiedBodies() {
        for (Body body : bodiesToRemoveList) {
            Array<Fixture> fixtures = body.getFixtureList();
            for (Fixture fixture : fixtures) {
                body.destroyFixture(fixture);
            }
        }
        bodiesToRemoveList.clear();
    }

What I'm doing is looping through all of the bodies in my bodiesToRemoveList. Then, each body has multiple fixtures, so I get all of them and loop through them, destroying each one. After all of this, I clear the bodiesToRemoveList. But, in my second for loop, when I destroy the fixtures, only one is getting destroyed. I did some debugging and found that the for loop only runs once. I'm not sure why this is happening. A google search showed other people with this issue, and I noticed they all removed or cleared items from a list, just like I'm doing. I see no issue with my code, but for some reason nothing I try will fix it. Does anybody seen any issue with my code? Thanks in advanced.

Edit: I'm an idiot. Thanks to everybody who helped. Here is my code, if anybody wants to see it.

public static void removeSpecifiedBodies() {
            Iterator<Body> i = bodiesToRemoveList.iterator();
            while (i.hasNext()) {
                Body desBod = i.next();
                //body.destroyFixture(fixture);
                WorldController.b2world.destroyBody(desBod);
                i.remove();
            }
        bodiesToRemoveList.clear();
    }

You shouldn't be modifying a list that you are iterating over, unless you're using an Iterator directly (and sharing it with the loop). Since you don't have access to the Iterator that the for loop is using, you are going to get mixed results, for sure.

So, either use the iterator directly, or another method is to accumulate all of the items you want removed from list in to a another collection, and then removeAll from the original collection. This is a bit more expensive as you are iterating across the list twice, but it's simple and clean and for short lists, likely not a real issue.

Otherwise:

List<Fixture> fixtures = body.getFixtureList();
Iterator<Fixture> i = fixtures.iterator();
while(i.hasNext()) {
    Fixture fixture = i.next();
    if (destroyFixture(fixture)) {
        i.remove();
    }
}

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