Home > Software design >  Java: toString method printing the hash code instead of inOrder traversal
Java: toString method printing the hash code instead of inOrder traversal

Time:02-28

I am trying to print the toString of BinarySearchTree(Generic), which contains in its body the following:

@Override
    public String toString() {
    root.inOrderTraversal(root);
    return  "inOrderTraversal has finished";
    }

and this is my inOrder traversal, which is inside the BinaryNode class (Generic), used by the BinarySearchTree:


public void inOrderTraversal(BinaryNode<T> node)
    {
        if(node != null)
        {
            if(node.left != null)
            {
                inOrderTraversal(node.left);
            }
            System.out.println(node.nodeValue);
            if(node.right != null)
            {
                inOrderTraversal(node.right);
            }
        }
    }

After I constructed the Generic BinarySerachTree using Student as its type and printed the toString, it is showing the output as Student@7a81197d, Student@5ca881b5, Student@24d46ca6. What could be the problem?


        Student s1 = new Student("Jasim", 84812); //Name and his/her ID
        Student s2 = new Student("Yousef", 845623);
        Student s3 = new Student("Zack", 432553);
        Student s4 = new Student("Zara", 54233);
        BinarySearchTree<Student> bst = new BinarySearchTree<Student>(s1); //construction
        bst.insert(s2);
        bst.insert(s3); 
        System.out.println(bst.toString()); //Error when printing this.

CodePudding user response:

i am assuming that your Student class has 2 attributes, in that case if you override toString() method into Student class then it will meet your expectation. i.e:

Class Student{
String name;
int id;
...........
...........
...........
@Override
public String toString() {
return "Name: " this.name ", Id: " this.id;
}

}

CodePudding user response:

How about consider another inner data structure? Deque can be great alternative to print value of student.

CodePudding user response:

I think you should implement toString() method in your Student pojo. Currently it is printing the object reference as per java notation

  • Related