[英]Java Class isntance(with ToString method overriding) outputs “adt.BinaryNode@1e24e45”
你好我已经在我自己的类中覆盖了toString()
方法,但不知何故输出并不是我想要的。 对不起新手问题,但我不知道问题出在哪里,任何提示/帮助主要是赞赏。 谢谢。
我的课:
public class Country implements Comparable<Country>{
private String name;
private String capital;
private int area;
public Country(String a, String b, int c) {
this.name = a;
this.capital = b;
this.area =c;
}
@Override
public String toString(){
return(this.name + " "+ this.capital+" " + this.area);
}
}
DS:
private void preorder(BinaryNode <type> a){
if (a != null){
System.out.println(a.toString());
preorder(a.left);
preorder(a.right );
}
}
应用程序:
BinarySearchTree <Country> db = new BinarySearchTree<Country>();
Country ob = new Country("Romania", "Buc", 123);
db.addNewElement(ob);
ob = new Country("Hungaria", "Bud", 50);
db.addNewElement(ob);
ob = new Country("Vatican", "Vat", 1);
db.addNewElement(ob);
db.printAll();
输出:
adt.BinaryNode@1e5e2c3
adt.BinaryNode@18a992f
adt.BinaryNode@4f1d0d
编辑:修复“chaitanya10”暗示msitake
DS:
private void preorder(BinaryNode <type> a){
if (a != null){
System.out.println(a.elm.toString()); // ACCES the data in node not the hole node.
preorder(a.left);
preorder(a.right );
}
}
你的方法以BinaryNode<type>
作为argument
,你在brinaryNode<type>
而不是COuntry
上调用toString
。 你在Country
not BinaryTree
overriden toString()
。 改为
private void preorder(Country a){
if (a != null){
System.out.println(a.toString());
}
}
或override toString() in BinaryNode
。
您正在调用BinaryNode的toString方法,而不是Country
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.