0

I'm implementing stacks in Java using linked lists and I'm still a beginner in programming.
I want to push an element into the stack but I'm getting this result, how do I solve it:
" Stack@15db9742 "

And this is my code:

public class Stack {
    class Element{
        int data;
        Element next = null;
        
        Element(int value){
            data = value;
            next = null;
        }
    }
    
    private Element head = null;
    
    public Stack() {
        head = null;
    }
    
    
    
    public boolean isEmpty() {
        return this.head == null;
    }
    
    public void push(int value) {
        Element tmp = new Element(value);
        tmp.next = head;
        head = tmp;
        
    }
    
    public void pop() {
        if(isEmpty())
            System.exit(1);
        head = head.next;
    }
    
    public int stackTop() {
        if(isEmpty())
            System.exit(2);
        return head.data;
    }
@Override
    public String toString() {
        return "Stack [head=" + head + "]";
    }
    
    public void makeEmpty() {

    }
    
    public int search(int value) {
        if(isEmpty())
            return -1;
        
        Element cur = head; // cur = cursor
        int n = 0;
        while(cur != null) {
            if(cur.data == value)
                return n;
            cur = cur.next;
            n++;
            
        }
        return n;
    }
    
    public static void main(String[] args) {
        Stack s1 = new Stack();
        
        s1.push(1);
        s1.push(2);
        s1.push(3);
        s1.push(4);
        s1.push(5);
        System.out.println(s1.toString());
    }

}

I would like also a hint if the "search" method is correct. I just can't tell if it's working before solving my initial problem.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
P_M
  • 42
  • 6
  • @Ivar I tried to implement the toString method but I still got the same error – P_M Apr 27 '21 at 19:39
  • 1
    It's the default implementation of `toString` for any `Object`. You need to implement a `toString` for *every* custom class, not only your `Stack` class – QBrute Apr 27 '21 at 19:44
  • 1
    To add to QBrute's comment, if you return `"Stack [head=" + head + "]"`, then `head` will also be converted to a string using the `toString()` of the `Element` class. If you don't have any there, you get the same problem. – Ivar Apr 27 '21 at 19:46

0 Answers0