0

I want to output the contents of each stack after the code below has executed. so far its outputting as

Stack@568db2f2
Stack@378bf509
Stack@378bf509

but I want the contents of each stack.

Code:

public static void main(String[] args) {
    Stack<Integer> a = new Stack<>();
    Stack<Integer> b = new Stack<>();
    Stack<Integer> c = new Stack<>();

    a.push(28);
    b.push(a.pop());
    b.peek();
    c.push(21);
    a.push(14);
    a.peek();
    b.push(c.pop());
    c.push(7);
    b.push(a.pop());
    b.push(c.pop());

    System.out.println(a);
    System.out.println(b);
    System.out.println(b);

}
Federico klez Culloca
  • 24,336
  • 15
  • 57
  • 93
EGS99
  • 13
  • 4

2 Answers2

0

Stack<E> is a subclass of Vector<E>, which you can use .size() and .elementAt(int index) on:

Stack<String> stack = new Stack<String>();
stack.push("!");
stack.push("world");
stack.push(" ");
stack.push("Hello");
for (int i = stack.size() - 1; i >= 0; --i) {
  System.out.print(i);
}
System.out.println();

As Federico pointed out however, if you don't care about emptying the stacks when printing them, then you can also just loop over them calling .pop() until they are empty.

However, as this answer points out, you should be using a Deque<E> instead of a Stack<E>. LinkedList<E> implements Deque<E>, and can easily be iterated over to print its elements (from top to bottom):

Deque<String> stack = new LinkedList<String>();
stack.push("!");
stack.push("world");
stack.push(" ");
stack.push("Hello");
for (String item : stack) {
  System.out.print(item);
}
System.out.println();
Billy Brown
  • 2,159
  • 22
  • 25
0

It seems like the default toString() for the class Stack prints the stack's location in the memory or something like that instead of printing the stack's contents. You should use the following code for each stack (stk is the original Stack taht you want to print its contents):

//Create another temporary Stack
Stack<Integer> temp = new Stack<>();

//Print each content of the original Stack (stk) separately.
//Move each content to the temporary Stack (temp), in order to preserve it.
while(! stk.empty())
   {
       System.out.println(stk.peek());
       temp.push(stk.pop());
   }

//Move all the content back to the original Stack (stk)
while(! temp.empty())
   {
       stk.push(temp.pop());
   }