Java类实例(包含ToString方法重写)输出“adt.BinaryNode@1e24e45”

4

你好,我在自己的类中覆盖了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 );
      }
} 

App:

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"的提示进行修正

数据科学:

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 );
      }
} 

1
BinarySearchTree 是哪个第三方库的?问题就出在这里。 - Jim Garrison
noop已经固定,需要使用nod.element.toString - Bogdan M.
2个回答

3
您的方法以BinaryNode<type>作为参数,您正在对binaryNode<type>而不是Country调用toString。您已在Country中重写了toString()而不是BinaryTree。 请修改为:
private void  preorder(Country a){
      if (a != null){
       System.out.println(a.toString());

      }
} 

或者在 BinaryNode 中重写 toString() 方法。


"preorder"是BinarySearchTree的一种方法,它不能特定地实现到"Country"...或者我漏掉了什么吗? - Ruan Mendes
@JuanMendes 说实话,我对二叉树的方法不熟悉,我只是指出他的错误 :) - PermGenError
1
@BogdanM。谢谢 :) 我希望你正在覆盖BinaryNode中的toString()方法 :) - PermGenError

2

您正在调用BinaryNode的toString方法,而不是Country。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接