I was trying to iterate over stack using iterator by:
Iterator it = stack.iterator();
while(it.hasNext())
System.out.print(it.next()+"\t");
I just have noticed that it is iterating in reverse order. Is it because iterator always points the start of a collection (for this case iterator is pointing the stating of the vector).
N.B: I know below code will give proper output for stack operation. I am curious about the iterator behavior.
Iterator it2 = stack.iterator();
while(it2.hasNext())
System.out.print(stack.pop()+"\t");
The iterator method in Stack is inherited from, not overridden in Vector, which would simply iterate through its elements in insert order. This is contrast to the order in which elements would be popped off of a stack. This is just normal Iterator behavior in Vector, which has nothing to do with Stack.
If you would like a more fully-functional Stack, use an implementation of the Deque interface, e.g. ArrayDeque. It implements stack and queue functionality at the same time. Because it pushes elements to the front of the Deque, the iterator, which processes elements from front to back, will give elements in the order that they would be popped from the stack.
Pushes an element onto the stack represented by this deque (in other words, at the head of this deque)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With