Why is my java stack not following the principle of LIFO while printing?
import java.util.*;
class StackTrace
{
public static void main(String []ar)
{
Stack myStack = new Stack();
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.push(4);
System.out.println(myStack);
Object Arr[]=myStack.toArray();
for(Object a:Arr)
System.out.println(a);
}
}
Output :
[1, 2, 3, 4]
1
2
3
4
In the above code, the statement System.out.println(myStack);
is printing data sequentially rather than last in first out manner.
Why so?
And also how is the toArray()
method working in the above program?