I already tried other ways, like using i--
but it did not work.
Reversing a for
loop consists of three steps:
- Change the initial value to the last value,
- Change the condition to stop after passing the initial value
- Reversing the increment/decrement (i.e.
++
becomes --
)
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();