As we know that stack is a data structure which follows LIFO order. And as per my knowledge stack allows to access top element only. But in Java we can use iterator with stack which somehow contradict the above idea of allowing access to only top element.
Sample code
Stack<Integer> s=new Stack<Integer>();
s.push(10);
s.push(20);
s.push(30);
------------------------------------------------------------------------
Iterator<Integer> itr=s.iterator();
while(itr.hasNext())
{
System.out.print(itr.next() + " "); // ouput:- 10 20 30
}
Now I have an iterator on stack which can traverse the stack in FIFO order and I can even delete any element by using itr.remove()
It's very confusing :)
Please explain...
PS: In case I use listIterator at the place of iterator then it's even more confusing because former one provides more methods.