javaiteration

Reverse the order of accessing a list in a Java for loop


I want to reverse the order of accessing a List inside a for statement.

This is my actual code:

for(int i = 0; i < states.size(); i++) {
    System.out.println(states.size());
    states.get(i).update(true); // restore the first blockstate
    states.remove(i); // remove the first blockstate from the list
}

This code works, but I would like to reverse it. I already tried other ways, like using i-- but it did not work. Can someone provide a suggestion?


Solution

  • I already tried other ways, like using i-- but it did not work.

    Reversing a for loop consists of three steps:

    In your code this change would look as follows:

    for(int i = states.size()-1 ; i >= 0 ; i--) {
        System.out.println(states.size());
        states.get(i).update(true); // restore the current blockstate
        states.remove(i); // remove the current blockstate from the list
    }
    

    Note that the last value reached in the original loop is states.size()-1, not states.size(), so i needs to start at states.size()-1 as well.

    Since your loop eventually clears out the list anyway, but does it one element at a time, you may get better clarity by deleting the call of remove(i), replacing it with states.clear() after the loop.

    for(int i = states.size()-1 ; i >= 0 ; i--) {
        System.out.println(states.size());
        states.get(i).update(true); // restore the current blockstate
    }
    states.clear();