0

在 Java 文件中,我有以下代码:

MyTree atree = new MyTree();
atree.insert(1);

这不是一棵普通的树。“atree”是根节点。这棵树中的每个节点都有 5 个孩子,最初都设置为 null。insert 的参数是您要“激活”的子项,即使其非空。所以我在 MyTree 类中有一个方法可以做到这一点:

public void insert(int i)
{
    if(i == 1)
    {
        MyTree current = this.getChildOne();
        current = new MyTree();
    }
}

调用该函数后,我检查文件中调用它的第一个节点。

if(atree.getChildOne() == null)
{
    return -1;
}

它总是返回负数。我怀疑插入函数实际上是在处理“atree”的副本,而不是实际的“atree”。但我并不完全确定。有人有解释吗?

4

2 回答 2

3

看起来您并没有在任何地方分配孩子。编码

MyTree current = this.getChildOne();
current = new MyTree();

不分配孩子一。您初始化了一个局部变量current,但是当方法结束时该变量会丢失。

我想你可能想在你的插入方法中做这样的事情

if ( i == i ) {
   this.childOne = // assign it here
}
于 2012-08-16T20:51:01.093 回答
0

该行current = new MyTree()更改了局部变量current:它曾经指向指向的实例this.getChildOne(),现在它指向一个新实例。(所以你最好取消赋值current = this.getChildOne():除非getChildOne有副作用,否则这个赋值是没有意义的,因为你会立即通过设置current其他东西来覆盖它。)

要实际修改 的某些属性this,您需要编写如下内容:

if(i == 1)
{
    this.setChildOne(new MyTree());
}
于 2012-08-16T20:50:49.117 回答