2

I want to reverse the order of accessing a List inside a for()

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?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
user3000019
  • 103
  • 1
  • 10

2 Answers2

6

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();
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Yhea thats working but how would u do a interval between each loop? i have a new regenBlock(states).runTaskTimer(this, 40, 17); but now isnt working it does the loop very fast – user3000019 Sep 29 '15 at 12:27
0

Try this:

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

if u want to remove element when accessing element then u have to use iterator by using simple for it is not possible... it throws concurrent modification exception

Pankaj Saboo
  • 1,125
  • 1
  • 8
  • 27