Java颠倒了在for循环中访问列表的顺序

use*_*019 2 java

我想颠倒在for()中访问List的顺序

这是我的实际代码

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
}
Run Code Online (Sandbox Code Playgroud)

这段代码有效,但我想反过来.我已经尝试过其他方式,比如使用,i--但它没有用.有人可以提出建议吗?

das*_*ght 5

我已经尝试过其他方式,比如使用,i--但它没有用.

反转for循环包括三个步骤:

  • 将初始值更改为最后一个值,
  • 传递初始值后,将条件更改为停止
  • 反转增量/减量(即++变为--)

在您的代码中,此更改将如下所示:

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
}
Run Code Online (Sandbox Code Playgroud)

请注意,原始循环中达到的最后一个值states.size()-1不是states.size(),因此i需要从头开始states.size()-1.

由于你的循环最终会清除列表,但是一次只能清除一个元素,你可以通过删除调用来获得更好的清晰度,在循环之后remove(i)替换它states.clear().

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();
Run Code Online (Sandbox Code Playgroud)