0

I have to create a method on stacks. For some reason when I try to execute from the main method it ALWAYS shows something like ArrayStack@6acbcfc0 even thought I take the answer from the answers sheet. What is wrong? This is my coding for the method and the main class.

Stack method:

public static void splitStack(ArrayStack<Integer> st1,ArrayStack<Integer> st2)
    {
        ArrayStack<Integer> st11 = new ArrayStack<Integer>();
        ArrayStack<Integer> st2rev = new ArrayStack<Integer>();
        while(!st1.isEmpty())
        {
            st11.push(st1.pop());
            if(!st1.isEmpty())
                st2rev.push(st1.pop());
        }
        while(!st11.isEmpty())
            st1.push(st11.pop());
        while(!st2rev.isEmpty())
            st2.push(st2rev.pop());

    }

main method:

public static void main(String[] args) {
      
        ArrayStack<Integer> s1 = new ArrayStack<>();
        ArrayStack<Integer> s2 = new ArrayStack<>();
        s1.push(0);
        s1.push(1);
        s1.push(3);
        s1.push(4);
        s1.splitStack(s1,s2);
        System.out.println(s2);
    }

output:

ArrayStack@6acbcfc0

Process finished with exit code 0

Kirby
  • 15,127
  • 10
  • 89
  • 104
  • You should override the `toString()` method of your `ArrayStack` class if you want a more meaningful output. – Eran Dec 22 '20 at 08:12
  • okay thanks, but how am i gonna do that ? what is the body of the ` toString() ` going to be? – Alooy DaBoss Dec 22 '20 at 09:02
  • *"what is the body of the ` toString() ` going to be?"* - Whatever you want! Its purpose is to render an instance of your class into a form that users can read. You can include as little or as much information in the result string as you want or need to. – Stephen C Dec 22 '20 at 10:15

2 Answers2

0

When you pass an object to System.out.println(), it tries to figure out what to do with it, i.e., which object type it is to pass to the method. If it can't figure anything else, it uses the object's toString() method (so it can pass a string to println()), and the output you've shown looks like the default output of toString() for an arbitrary object. If you override toString() in your class, then when println() invokes it it will execute your code instead of the default code.

arcy
  • 12,845
  • 12
  • 58
  • 103
0

Try to use s2.toString() in System.out.println() statement which is in main method.

like - System.out.println(s2.toString());