简体   繁体   中英

why this java code does not work?

I have this code fragment

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

When I call the insert function like insert(5); insert(8); insert(5); insert(8); it alwaty prints root is null .

whats the problem??

Your problem is that ro variable inside the insert method is just a copy of the reference to bst.ro . Meaning that if you reset the ro variable inside the method, just the copy of the reference will point the new ro , the originally passed object will remain the same.

Your question is the top 1 of Parameter Passing FAQ. I myself already answered this question more than once. Check it out .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM