I'm migrating a piece of code to make use of generics. One argument for doing so is that the for loop is much cleaner than keeping track of indexes, or using an explicit iterator.
In about half the cases, the list (an ArrayList) is being iterated in reverse order by using an index.
Can someone suggest a cleaner way of doing this (since I dislike the indexed for loop when working with collections)?
for (int i = nodes.size() - 1; i >= 0; i--) {
final Node each = (Node) nodes.get(i);
...
}
Note: I can't add any new dependencies outside the JDK.
Took accepted answer and turned it into:
class ListReverser<T> implements Iterable<T> {
private ListIterator<T> listIterator;
public ListReverser(List<T> wrappedList) {
this.listIterator = wrappedList.listIterator(wrappedList.size());
}
public Iterator<T> iterator() {
return new Iterator<T>() {
public boolean hasNext() {
return listIterator.hasPrevious();
}
public T next() {
return listIterator.previous();
}
public void remove() {
listIterator.remove();
}
};
}
}
Which can be used as:
for (final Node each : new ListReverser<Node>(nodes)) {
//...
}
Not great, but better.