Java: toString方法打印哈希码而不是inOrder遍历

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

我正在尝试打印 BinarySearchTree(Generic) 的 toString,它的正文中包含以下内容:

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

这是我的 inOrder 遍历,它在 BinaryNode class(通用)内部,由 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);
            }
        }
    }

在我使用 Student 作为其类型构造 Generic BinarySerachTree 并打印 toString 之后,它显示输出为 Student@7a81197d、Student@5ca881b5、Student@24d46ca6。 可能是什么问题?


        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.

我认为您应该在 Student pojo 中实现 toString() 方法。 目前它正在按照 java 表示法

打印对象引用

如果你的导师保持原来的要求,你可以尝试以下方法: `

public class StudentModal extends Student{
    public StudentModal( String name, Integer id) {
        super(name, id);
    }

    @Override
    public String toString() {
        return "userName:" + this.getName() + "id:" +this.getId();
    }
}
public static void main(String[] args) {
    StudentModal student = new StudentModal("test", 1);
    System.out.println(student);
}

`