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
  • 26,308
  • 17
  • 56
  • 95
EGS99
  • 13
  • 4
  • If you don't need the stacks to still be filled at the end of the program you can `pop` one element at a time (until the stack is empty) and print it. – Federico klez Culloca Oct 23 '20 at 07:58
  • what type of output you are expecting for contents of each stack ? `String` [28, 21, 14, 7] ? – Akila Oct 23 '20 at 08:00
  • @aKilleR would they all end up empty? – EGS99 Oct 23 '20 at 08:04
  • @EGS99 , Will not be empty if you use `peek()` Check [This](https://stackoverflow.com/questions/12160183/java-printing-the-stack-values) out – Akila Oct 23 '20 at 10:54

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,272
  • 23
  • 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());
   }