为什么这段java代码不起作用?
我有这个代码片段
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
函数时, insert(8);root is null
。
有什么问题吗?
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);
it alwaty prints root is null
.
whats the problem??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题是
insert
方法中的ro
变量只是对bst.ro
引用的副本。这意味着,如果您在方法内重置ro
变量,则引用的副本将指向newro
,原来传递的对象将保持不变。您的问题是参数传递常见问题解答中的第 1 个问题。我自己已经不止一次回答过这个问题了。 查看一下。
Your problem is that
ro
variable inside theinsert
method is just a copy of the reference tobst.ro
. Meaning that if you reset thero
variable inside the method, just the copy of the reference will point the newro
, 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.