首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >以getter作为参数调用函数不会保留引用?

以getter作为参数调用函数不会保留引用?
EN

Stack Overflow用户
提问于 2019-03-28 23:39:44
回答 1查看 40关注 0票数 0

我的代码有一个问题,我创建了一个二进制搜索树数据结构,当我调用一个带有节点的子节点的函数,然后在函数中为这个子节点赋值时,它不会更新节点的子节点。

代码语言:javascript
复制
//*** Pseudo-ish Code ***

class BSTNode {

    private BSTNode lChild;
    private BSTNode rChild;
    private int key;

    public BSTNode(int key) {
        this.lChild = null;
        this.rChild = null;
        this.key = key;
    }

    //getters and setters for each field ^
}

class BST {

    private BSTNode root;

    public BST() {
        this.root = null;
    }

    public void insert(BSTNode currentNode, int value) {

        BSTNode newNode = new BSTNode(value);

        if (currentNode == null) {

            currentNode = newNode;
            if (this.root == null) {
                this.root = currentNode;
            }

        } else {

            //ignore the newNode == currentNode value statement right now

            if (newNode.getValue() < currentNode.getValue()) {
                insert(currentNode.getlChild(), value);
            } else if (newNode.getValue() > curNode.getValue()) {
                insert(curNode.getrChild(), value);
            }
        }
    }

    //getters and setters
}

我仍然想自己弄清楚代码,但我很好奇为什么我要用以下命令运行这段代码:

代码语言:javascript
复制
BST testBST = new BST();

testBST.insert(testBST.getRoot(), 10);
testBST.insert(testBST.getRoot(), 7);

System.out.print(testBST.getRoot()); 
System.out.print(" ");
System.out.print(testBST.getRoot().getlChild());

这将输出10,然后输出一个NullPointerException。我理解这是因为不知何故7没有被分配为10的lChild,但我不知道为什么?是我遇到了作用域问题,还是因为我在插入函数中递归调用了getlChild(),所以无法访问实际的私有lChild字段?

注意:我正在使用sysout调试我的代码,我注意到递归确实起作用了,并且它确实将7正确地分配给了currentNode,但是一旦函数运行完毕,就像currentNode不再引用初始根节点的lChild。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55401626

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档