【问题标题】:why this java code does not work?为什么这个java代码不起作用?
【发布时间】:2010-01-17 14:31:01
【问题描述】:

我有这个代码片段

class bst {
  public node root=null;

  bst() {
    root=null;
  }

  public void insert(int data) {  
    insert(this.root,data);
  }

  private void insert(node ro,int data) {
    if (ro==null) {
      print ("root is null");
      ro=new node(data);
    } else if (data>ro.data)
      insert(ro.right,data); 
    else
      insert(ro.left,data);
  }

  private void print (String str) 
  {
    System.out.println(str);
  }
}

当我像insert(5); insert(8); 这样调用insert 函数时,它总是打印root is null

什么问题??

【问题讨论】:

  • 下次请确保您的帖子可读。该代码是一个可怕的混乱,因为你发布是作为一个引用,你甚至没有得到语法突出显示。
  • 你应该学会更好地缩进你的代码!
  • insert 不是函数,而是方法。
  • Java 是按值传递,而不是按引用传递。
  • 方法无论如何都是成员函数

标签: java binary-search-tree


【解决方案1】:

您的问题是insert 方法中的ro 变量只是对bst.ro 的引用的副本。这意味着如果您重置方法内的ro变量,只是引用的副本将指向new ro,最初传递的对象将保持不变.

您的问题是参数传递常见问题解答的前 1 个问题。我自己已经不止一次地回答了这个问题。 Check it out.

【讨论】:

    猜你喜欢
    • 2018-11-05
    • 2012-02-22
    • 2023-03-03
    • 2017-10-02
    • 2016-07-10
    • 2010-12-14
    • 2017-04-09
    • 2013-01-30
    • 2014-05-23
    相关资源
    最近更新 更多