1

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?

CCovey
  • 799
  • 1
  • 10
  • 17
konyviji
  • 11
  • 2

3 Answers3

1

toArray method will return the array of elements in the order they were inserted to stack. If you need the elements in LIFO use the pop method. You can go through Stack api here,

http://docs.oracle.com/javase/6/docs/api/java/util/Stack.html

Santo
  • 362
  • 1
  • 4
  • 18
1

I'll start off by saying that, like you, this annoyed me. A stack in it's most primal sense isn't able to access elements other than the top element. As far as I can tell, the only logic behind this is that java is treating this the way it is stored.

As for the storage of a Stack in Java, it stores in much the same way as an ArrayList (using an array, doubling when it fills). Similarly, the toString of Stack comes from Vector (similar to an ArrayList), which starts at the beginning. Since the "top" of the stack is the end, it gets outputted last.

Here's some example code:

import java.util.*;
public class StacksTesting
{
    public static void main(String[] args)
    {
        Stack<Integer> st = new Stack<Integer>();
        for(int i=0; i<10; i++)
            st.add(i);
        System.out.println(st);   
        while(!st.isEmpty())
           System.out.print(st.pop()+" ");
    }
}

Will give:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9 8 7 6 5 4 3 2 1 0 

as output

TMR
  • 96
  • 5
0

Q: Why is my java-stack not following the principle of LIFO while printing?

The class Stack is an extension of the class Vector that can be found in java.util.*;.

Using the class Stack included in the Java API is not a good way to implement a Stack in Java.

The class Vector has become obsolete. Saying that a Stack is a Vector breaks the OOP principle of encapsulation. You only want to be able to access the top of the Stack. However, because your Stack is a Vector, it inherits undesirable methods from the class Vector.

See Oracle's Java documentation here:

So you can call the Vector methods, in addition to the Stack methods of peek(), pop(), push() and empty(). This will allow you to access more than just the top of the Stack, or print the entire Stack.

To fix this, you have to write your own Stack class. You can try implementing your Stack as an Array, a LinkedList, a Deque or using a List interface.

Community
  • 1
  • 1
CCovey
  • 799
  • 1
  • 10
  • 17