Reputation: 103
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?
Upvotes: 2
Views: 139
Reputation: 21347
for (ListIterator<State> i = states.listIterator(states.size()); i.hasPrevious(); ) {
State value = i.previous();
System.out.println(states.size());
value.update(true); // restore the first blockstate
i.remove(); // remove the first blockstate from the list
}
Your stated desired code iterates over each element of the list in reverse order, and does the following things for each element it accesses:
update
method on the current elementThe ListIterator
class allows iterating over the list in reverse order, accessing each element, and removing the current element from a list. It can therefore be used to achieve your stated goals.
Upvotes: 0
Reputation: 1185
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
Upvotes: 0
Reputation: 727047
I already tried other ways, like using
i--
but it did not work.
Reversing a for
loop consists of three steps:
++
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();
Upvotes: 6