Java:toString方法打印哈希码而不是inOrder遍历
我正在尝试打印 BinarySearchTree(Generic) 的 toString,其主体中包含以下内容:
@Override
public String toString() {
root.inOrderTraversal(root);
return "inOrderTraversal has finished";
}
这是我的 inOrder 遍历,它位于 BinaryNode 类 (Generic) 内部,由 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 作为其类型并打印了 toString,它显示输出为 Student@7a81197d、Student@5ca881b5,学生@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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你的导师维持原来的要求,你可以尝试以下方法:
`
`
If your instructor maintains the original requirements, you can try the following:
`
`
我认为你应该在你的 Student pojo 中实现 toString() 方法。
目前它正在按照 java 表示法打印对象引用
I think you should implement toString() method in your Student pojo.
Currently it is printing the object reference as per java notation