Search code examples
javabinary-search-treetostring

Java: toString method printing the hash code instead of inOrder traversal


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.

Solution

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