Home  >  Q&A  >  body text

java编程,函数内变量传递问题,为什么没有都改变呢?

代码如下:

public void test(BSTNode<T> z)
    {
        BSTNode<T> y;
        if (z.left != null){
            y = z.parent;
            BSTNode<T> a;
            a = y.left;
            if (y != null){
                System.out.println("before a             "+a);
                System.out.println("before y.left        "+y.left);
                System.out.println("befere z.parent.left "+z.parent.left);
                y.left = null;
                //a = null;
                System.out.println("after a              "+a);
                System.out.println("after y.left         "+y.left);
                System.out.println("after z.parent.left  "+z.parent.left);
            }
        }
    }

打印结果如下:
before a threadSleep.BSTree$BSTNode@15db9742
before y.left threadSleep.BSTree$BSTNode@15db9742
befere z.parent.left threadSleep.BSTree$BSTNode@15db9742
after a threadSleep.BSTree$BSTNode@15db9742
after y.left null
after z.parent.left null

请问 “after a ”为什么不是null?

或者将代码:

y.left = null;

            //a = null;

改为

//y.left = null;

a = null;

结果为:

before a threadSleep.BSTree$BSTNode@15db9742

before y.left threadSleep.BSTree$BSTNode@15db9742

befere z.parent.left threadSleep.BSTree$BSTNode@15db9742

after a threadSleep.BSTree$BSTNode@15db9742

after y.left null

after z.parent.left null

运行环境:

jdk1.8

阿神阿神2743 days ago589

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-04-18 10:53:11

    Your results will definitely be different twice. In fact, it is the same as the one below.

    
    int x = 10;
    int y = x;
    y = 0;
    x ?

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:53:11

    Passing by reference in Java is essentially passing the address of the object. The address is actually passed by value. Through this address, the value of the object pointed to in the memory can be modified. Changing the value of this address makes no sense except losing control of the real object.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:53:11

    I’m coming, I’m coming

    It’s very simple. You only need to understand that passing by reference transfers an address. After this address is passed, it will be placed in the local variable of the called method. There are two stack frames for the two methods, and each stack frame has its own local variable tables, do not affect each other. So this is why you pass a reference and then change the reference point to have no image of the original one.

    So, why does the value of val change when obj.val is modified? Because the value of val is stored in the heap. It is copied, modified, and then written back to the heap, so it changes. If you don’t understand, you can continue to ask questions

    reply
    0
  • Cancelreply