Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why stack iterator works in reverse order?

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");
like image 439
ratulalahy Avatar asked Apr 25 '26 19:04

ratulalahy


1 Answers

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)

like image 110
rgettman Avatar answered Apr 28 '26 07:04

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!