自自然卷 2017-02-11 08:48 采纳率: 35.7%
浏览 4173

java子函数中修改引用的值

假设某一对象的一个引用是A,如果想要在子函数f()里修改引用的值怎么办?不是修改A所指
对象的值,不使用全局变量。
感觉说的不清楚,上代码:
先是正确代码:

 public class Solution {
    TreeNode listTail = null;
    public void inorder(TreeNode root){
        if(root == null)    return;
        if(root.left != null){
            inorder(root.left);
        }
        root.left = listTail;

        if(listTail != null){
            listTail.right = root;
        }
        listTail = root;
        if(root.right != null){
            inorder(root.right);
        }
    }
    public TreeNode Convert(TreeNode root) {
        if(root == null)    return null;
        inorder(root);
        TreeNode head = listTail;
        while(head.left != null){
            head = head.left;
        }
        return head;
    }
}

然后是错误代码:

 public class Solution {
    public void inorder(TreeNode root, TreeNode listTail){
        if(root == null)    return;
        if(root.left != null){
            inorder(root.left,listTail);
        }
        root.left = listTail;

        if(listTail != null){
            listTail.right = root;
        }
        listTail = root;
        if(root.right != null){
            inorder(root.right,listTail);
        }
    }
    public TreeNode Convert(TreeNode root) {
        if(root == null)    return null;
        TreeNode head = null;
        inorder(root,head);
        while(head != null && head.left != null){
            head = head.left;
        }
        return head;
    }

}

如果我想像错误代码那样写,调用这种形式的函数public void inorder(TreeNode root, TreeNode listTail,然后在函数内部修改listTial本身而不是其指向的对象,应该怎么做,但是不要用正确代码里使用成员变量的方法

  • 写回答

3条回答 默认 最新

  • 毕小宝 博客专家认证 2017-02-11 08:59
    关注

    首先,Java没有子函数的概念,函数就是类的成员方法。
    其次,你想在这个类的成员函数f里面修改引用的值是什么意思,是修改这个引用A的指针地址呢,还是修改A的属性的值呢?
    如果是想改变A的引用地址的话,直接重新赋值新的指针给这个A成员遍历就可以了。

    评论

报告相同问题?

悬赏问题

  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示