Why do I get this : [LMyStack.Node@addbf1 when I try to print right values of Stack?

StackOverflow https://stackoverflow.com/questions/23494765

  •  16-07-2023
  •  | 
  •  

Question

Here is my Java code to create a Stack and pop one Node from Stack. But when I added Nodes to Node[], the values I get when I print to the screen are : [LMyStack.Node;@addbf1.

I don't know what is problem. Any help?

 public class MyStack{
    private Node[] values;
    public MyStack(){

    }
    public MyStack(Node[] values){
        this.values=values;
    }
    //pop one Node from Stack
    public Node pop(){
        Node result=null;
        if(values!=null && values.length-1>0){
            result = values[values.length-1];
            Node[] temp = new Node[values.length-1];
            for(int i=0;i<values.length-1;i++){
                temp[i]=values[i];
            }
            this.values=temp;
            //Print the stack to screen
            System.out.println("The stack is:"+this.value); 
        }

        return result;

    }
}
class Node {
    private int value;
    public Node(){
        value=0;
    }
    public Node(int value){
        this.value=value;
    }
}
class Result{
    public static void main(String []args){
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        //Here is problem
        Node[] n = {node1, node2, node3};
        //System.out.println("Node is: "+n[1] );
        MyStack stack = new MyStack(n);
        stack.pop();
    }
}
Était-ce utile?

La solution

There are many examples of this on Stack Overflow. Please remember to search first!

What you're seeing is the default toString() method called on an array of Node objects. [LMyStack.Node indicates array of Node instances and addbf1 is the hexadecimal representation of the hashcode. Use a loop:

for (Node node : values) {
    System.out.println(node);
}

Autres conseils

System.out.println("The stack is:"+this.value); by default will be considered as System.out.println("The stack is:"+this.value.toString()); at run-time which returns classname@hashcode

default toString() implementation in Object calls it..

 public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top